我一直在使用Android的Google设计支持库。为了将按钮的颜色与应用程序主题不同,我在布局XML文件中声明按钮如下:
<Button
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="@style/MyButton" />
然后在styles.xml中定义MyButton:
<style name="MyButton" parent="ThemeOverlay.AppCompat">
<item name="colorButtonNormal">@color/my_color</item>
</style>
这将为我提供一个与设计支持库相符的按钮,背景颜色是在我的colors.xml文件中使用@color/my_color
定义的颜色。
因此,基本上是使用android:theme
来更改colorButtonNormal
属性以获取所需的颜色。
我如何以编程方式实现相同的结果?基本上,如果我可以做一些像下面这样的事情
myButton.setTheme(R.style.MyButton)
如果我能够设置colorButtonNormal
来获取视图,那就好了。
但是我不能像这样设置它:
myButton.setBackgroundColor(ContextCompat.getColor(getContext(),R.color.my_color));
或者甚至不喜欢
ColorStateList colorStateList = ContextCompat.getColorStateList(getActivity(), R.color.my_color);
ViewCompat.setBackgroundTintList(myButton, colorStateList);
这将移除设计支持库对触摸的影响。