【问题标题】:Make a button with custom icon on Android在Android上制作一个带有自定义图标的按钮
【发布时间】:2018-04-11 07:37:55
【问题描述】:

我正在开发一个 android 应用程序并想添加一个带有图标的button(小部件?)。 据我了解,它的外观应在xml 资源中进行描述。 我可以在java 代码中做到这一点,但它似乎不正确。

public class VideoButton extends android.support.v7.widget.AppCompatButton {
 private void onCreate(){
    setBackground(ResourceManager.getDrawable(R.mipmap.roundbackgroundnormal));
    Drawable icon = ResourceManager.getDrawable(R.mipmap.video);
    icon.setBounds(6,0,50,44);
    setCompoundDrawables(icon,null,null,null);
    setPadding(12,8,8,8);
...

所以,我写了一个不符合我期望的 xml 替换代码

        <blah.blah.blah.ui.widgets.VideoButton
            android:id="@+id/record"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:background="@mipmap/roundbackgroundnormal"
            android:drawableStart="@drawable/video"
            android:visibility="visible" />

我期待这个(ty java),

但是得到这个

如何修复我的 xml 代码以获得正确的结果? TY,如果可能,请修正术语。

【问题讨论】:

  • 我建议您考虑使用 @Nilesh 建议的浮动操作按钮(针对您的特定情况)。为什么?因为您正在混合背景和可绘制的图像作为您的图标。因此,您有一个问题,您需要使用 drawableStart/End/Top/Bottom 并使用在不同的屏幕密度上永远不会看起来不错的填充进行破解。您的另一个选择是创建一个 xml 可绘制文件,该文件将包含您的图标和您选择的背景颜色,并将其设置为自定义按钮的背景。

标签: android android-layout button resources icons


【解决方案1】:

最好使用FloatingActionButton

浮动操作按钮用于一种特殊类型的提升操作。它们通过悬浮在 UI 上方的带圆圈图标来区分,并具有与变形、启动和转移锚点相关的特殊运动行为。

编译这个依赖

compile 'com.android.support:design:27.0.2'

示例代码

<android.support.design.widget.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:src="@drawable/ic_check_box_black_24dp" />

结果


你可以使用ImageButton

显示一个带有用户可以按下或单击的图像(而不是文本)的按钮。默认情况下,ImageButton 看起来像一个普通的 Button,标准的按钮背景会在不同的按钮状态下改变颜色。按钮表面上的图像由 XML 元素中的 android:src 属性或 setImageResource(int) 方法定义。

示例代码

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_check_box_black_24dp" />

输出

【讨论】:

    【解决方案2】:
    <blah.blah.blah.ui.widgets.ViseoButton
            android:id="@+id/record"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:background="@mipmap/roundbackgroundnormal"
            android:drawableStart="@drawable/video"
            android:visibility="visible" />
    

    您可以使用自定义 icon.png 进行设计并将其移动到您的项目文件夹中 mipmap

    android:background="@mipmap/roundbackgroundnormal"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 2020-11-04
      相关资源
      最近更新 更多