在今天AppCompat更新出来之前,我可以改变Android L中按钮的颜色,但在旧版本上不行。在包含新的AppCompat更新后,我无法更改两个版本的颜色,当我尝试时,按钮就消失了。有人知道怎么改变按钮的颜色吗?
下面的图片展示了我想要达到的目标:
白色按钮是默认的,红色按钮是我想要的。
这是我之前在styles.xml中改变按钮颜色所做的:
<item name="android:colorButtonNormal">insert color here</item>
要动态地进行:
button.getBackground().setColorFilter(getResources().getColor(insert color here), PorterDuff.Mode.MULTIPLY);
我也改变了@android:style/ theme . material . light的主题父元素。到Theme.AppCompat.Light.DarkActionBar
我刚刚创建了一个android库,它允许您轻松地修改按钮颜色和波纹颜色
https://github.com/xgc1986/RippleButton
<com.xgc1986.ripplebutton.widget.RippleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="Android button modified in layout"
android:textColor="@android:color/white"
app:buttonColor="@android:color/black"
app:rippleColor="@android:color/white"/>
你不需要为每个你想要不同颜色的按钮创建一个样式,允许你随机自定义颜色
For me, the problem was that in Android 5.0 the android:colorButtonNormal had no effect, and actually, no item from the theme (like android:colorAccent), but in Android 4.4.3, for example, did. The project was configured with compileSdkVersion and targetSdkVersion to 22, so I've made all the changes as @Muhammad Alfaifi sugessted, but in the end, I've noticed that the problem was the buildToolsVersion, that wasn't updated. Once I changed to 23.0.1, everything start working almost as normal. Now, the android:colorButtonNormal still has no effect, but at least the button reacts to android:colorAccent, which for me is acceptable.
我希望这个提示能帮助到一些人。
注意:我已经将样式直接应用到按钮上,因为按钮的android:theme=[…]也没有效果。
要支持彩色按钮,请使用最新的AppCompat库(>23.2.1):
膨胀- XML
AppCompat小部件:
android.support.v7.widget.AppCompatButton
AppCompat风格:
style="@style/Widget.AppCompat.Button.Colored"
NB !在xml中设置自定义颜色:使用attr: app而不是android
(使用alt+输入或声明xmlns:app="http://schemas.android.com/apk/res-auto"使用app)
应用:backgroundTint = " @color / your_custom_color”
例子:
<android.support.v7.widget.AppCompatButton
style="@style/Widget.AppCompat.Button.Colored"
app:backgroundTint="@color/your_custom_color"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Colored Button"/>
或者以编程方式设置- JAVA
ViewCompat.setBackgroundTintList(your_colored_button,
ContextCompat.getColorStateList(getContext(),R.color.your_custom_color));