小编Tej*_*ala的帖子

使用 AppCompat 的设计效果为 Android Button 以编程方式设置 buttonColorNormal

我一直在使用适用于 Android 的 Google 设计支持库。为了设置与应用程序主题不同的按钮的颜色,我在布局 XML 文件中声明按钮如下:

<Button
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:theme="@style/MyButton" />
Run Code Online (Sandbox Code Playgroud)

然后将styles.xml中的MyButton定义为

<style name="MyButton" parent="ThemeOverlay.AppCompat">
    <item name="colorButtonNormal">@color/my_color</item>
</style>
Run Code Online (Sandbox Code Playgroud)

根据设计支持库,这给了我一个按钮,背景颜色与@color/my_color我的colors.xml 文件中定义的颜色相同。

因此基本上它是用来android:theme改变colorButtonNormal属性以获得所需的颜色。

我怎样才能以编程方式获得相同的结果?基本上,如果我可以做类似的事情

myButton.setTheme(R.style.MyButton) 
Run Code Online (Sandbox Code Playgroud)

...然后我可以设置colorButtonNormal以获得视图。

我不能设置它喜欢

myButton.setBackgroundColor(ContextCompat.getColor(getContext(),R.color.my_color));
Run Code Online (Sandbox Code Playgroud)

甚至不喜欢

ColorStateList colorStateList = ContextCompat.getColorStateList(getActivity(), R.color.my_color);
ViewCompat.setBackgroundTintList(myButton, colorStateList);
Run Code Online (Sandbox Code Playgroud)

这将移除触摸的设计支持库效果。

android material-design androiddesignsupport

5
推荐指数
1
解决办法
720
查看次数