【问题标题】:How to resize and change color of icon in a button?如何调整按钮中图标的大小和颜色?
【发布时间】:2018-07-02 12:09:29
【问题描述】:

我在 android 按钮中使用 android:drawableLeft="@mipmap/share_icon" 来显示图标。我想改变图标的​​颜色和大小。下面是我的代码

<Button
        style="@android:style/Widget.Holo.Light.Button.Small"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal"
        android:layout_marginBottom="15dp"
        android:background="#66ccff"
        android:clickable="true"
        android:drawableLeft="@mipmap/share_icon"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:text="Send An Invite"
        android:textColor="@color/white_color"
        android:textSize="18sp"
        android:textStyle="normal"
        android:tint="@color/white_color"
        />

【问题讨论】:

  • 你的源图标是什么?是矢量 xml 还是 jpg/png?
  • 是动态更改还是保持静态?
  • 我的源图标是 png 格式
  • 您能否详细说明您的问题。到目前为止,您为解决问题所做的尝试。请在您的问题中提及所有这些内容。

标签: android android-button android-icons


【解决方案1】:

在 mipmap 中打开 share_icon 的 xml 文件并从那里更改颜色和调整大小。

【讨论】:

    【解决方案2】:

    注意: mipmap 文件夹仅用于放置您的应用程序/启动器图标(显示在主屏幕上)。任何其他可绘制资产 你使用的应该像以前一样放在相关的drawable文件夹中。

    按照以下步骤操作:

    第 1 步

    将您的资源包装在一个可定义您所需大小的可绘制对象中,类似于:

     <?xml version="1.0" encoding="utf-8"?>
     <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    
          <item
             android:drawable="@drawable/{your icon}"
             android:width="@dimen/icon_size"
             android:height="@dimen/icon_size" />
    
     </layer-list >
    

    第 2 步

    从您的Button 中删除android:drawableLeft 标签

    第 3 步

    将此代码添加到您的Activity / Fragment

    int tintColor = ContextCompat.getColor(context,
    android.R.color.{your button color});
    
    Button button = (Button) findViewById(R.id.{your button id});
    
    Drawable drawable = ContextCompat.getDrawable(context, R.drawable.{drawable that you made earlier});
    
    drawable = DrawableCompat.wrap(drawable);
    DrawableCompat.setTint(drawable.mutate(), tintColor);
    
    drawable.setBounds( 0, 0, drawable.getIntrinsicWidth(), 
    drawable.getIntrinsicHeight());
    
    button.setCompoundDrawables(drawable, null, null, null);
    

    记住:假设你不知道

    • 要使上述代码正常工作,您应该将id 添加到您的Button
    • 如果您使用的是 Activity,请使用 getApplicationContext(),如果您使用的是 Fragment,请使用 getContext()
    • 将所需的颜色添加到colors.xml 文件中

    【讨论】:

      猜你喜欢
      • 2013-03-17
      • 2019-08-29
      • 1970-01-01
      • 2015-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-24
      相关资源
      最近更新 更多