【问题标题】:How to change color of material design icon used in Button in Android如何更改Android中Button中使用的材料设计图标的颜色
【发布时间】:2017-05-19 14:14:34
【问题描述】:

我的 XML 中有这个 Button

<Button
     android:id="@+id/button_message_me"
     style="@style/Widget.AppCompat.Button.Borderless.Colored"
     android:layout_width="0dp"
     android:layout_weight="0.25"
     android:layout_height="wrap_content"
     android:adjustViewBounds="true"
     android:background="@drawable/ic_chat_white_48dp"
     android:onClick="clickMessageMe"/>

但是,我想将ic_chat_white_48dp 的颜色从白色更改为蓝色。怎么改?

到目前为止我已经尝试过的:

阅读this 的帖子后,我尝试使用android:tint="@color/blue",但没有成功。

因此,考虑到我可能需要使用ImageButton 而不是Button(如answer 中所述),我在我的XML 中将Button 替换为ImageButton,但我得到了异常:

java.lang.RuntimeException:无法启动活动 组件信息{chat.knowme.knowme/chat.knowme.knowme.ShowProfileActivity}: java.lang.ClassCastException: android.support.v7.widget.AppCompatImageButton 无法转换为 android.widget.Button

任何帮助将不胜感激。非常感谢!

更新: 崩溃是因为我在源代码中将ImageButton 转换为Button。我修复了它,现在不再崩溃了(感谢 Patel Pinkal 的回答)。

但是,即使使用ImageButton,颜色仍然保持不变

【问题讨论】:

  • 发布你的Button初始化代码
  • 这个按钮没有初始化代码。每当我想显示/隐藏此按钮时,我都会使用(Button) findViewById(R.id.button_message_me);。并为按钮编写了clickMessageMe 方法。但是,一旦我启动活动,就会发生崩溃。
  • 你在用什么ImageButtonAppCompatImageButton

标签: android icons material-design android-appcompat


【解决方案1】:

我也面临这个问题。终于找到了解决办法,使用Android Material Design Icon Generator Plugin。通过这个,您可以生成各种颜色和大小的图标。

第一步:文件->设置->插件

第二步:搜索android material icon,列表中会出现Android Material Design Icon Generator Plugin

第三步:选择它并点击应用

安装后,从工作室右键单击您的项目->新建->材料设计图标或 ctrl+alt+M

它将对开发人员有用。

【讨论】:

  • 这确实是个好建议。如果我不能通过代码改变颜色,我肯定会这样做。
【解决方案2】:

您正在尝试初始化 Button 而不是 AppCompatImageButton。换成这样就行了

 AppCompatImageButton appCompatImageButton = (AppCompatImageButton) findViewById(R.id.appCompatImageButton);

而不是:

 Button button = (Button) findViewById(R.id.button);

如果您想使用ButtonAppCompatImageButton 更改颜色, 你必须改变像

android:backgroundTint="@Color/yourColor"

代替

android:tint="@Color/yourColor"

【讨论】:

  • 哦,我明白了。当然我会尝试这可能是原因:)
  • @Atul 在这里试用并查看
  • 嗯,我试过了。崩溃消失了,但颜色仍然没有改变。
  • 不确定我是否可以发布代码和布局等。需要检查。不过,我会试试你的新建议。谢谢老兄。
  • 不。它只适用于更高版本吗?我收到Attribute backgroundTint is only used in API level 21 and higher (current min is 15
猜你喜欢
  • 2015-08-13
  • 2021-05-14
  • 2015-08-15
  • 2015-06-29
  • 2015-10-30
  • 2016-02-25
  • 2014-10-12
  • 1970-01-01
  • 2015-03-14
相关资源
最近更新 更多