Kotlin Android开发中不修改colorPrimary如何单独更改按钮颜色
解决方案
方法1:直接覆盖按钮的背景着色属性
当前安卓新建项目默认使用MaterialComponents主题,普通Button会自动替换为MaterialButton,其背景色优先级最高的控制属性是app:backgroundTint,你之前设置的android:background会被该属性的默认值(也就是主题里的colorPrimary)覆盖,直接给目标按钮单独加这个属性即可生效,不会影响全局其他按钮:
<Button android:id="@+id/btn_black" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="黑色按钮" app:backgroundTint="@color/black" />
如果需要用自定义drawable作为按钮背景,不想被着色覆盖,可以把app:backgroundTint设为@null,此时android:background属性就会正常生效:
<Button android:id="@+id/btn_custom" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="自定义背景按钮" android:background="@drawable/custom_button_shape" app:backgroundTint="@null" />
注意:需要在布局文件的根节点声明xmlns:app="http://schemas.android.com/apk/res-auto"命名空间,否则app:开头的属性无法识别。
方法2:给单类按钮指定自定义样式
如果有多个按钮需要复用相同的配色,可以在styles.xml中定义独立的按钮样式,只给需要的按钮引用即可:
- 首先定义自定义样式
<style name="BlackButtonStyle" parent="Widget.MaterialComponents.Button"> <item name="backgroundTint">@color/black</item> <item name="android:textColor">@color/white</item> <!-- 可自定义其他专属属性 --> </style>
- 布局中给目标按钮引用样式
<Button android:id="@+id/btn_black" style="@style/BlackButtonStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="黑色按钮" />
方法3:使用AppCompatButton(可选)
如果不需要MaterialComponents的波纹、圆角等默认特效,也可以直接使用AppCompatButton控件,此时android:background属性会直接生效:
<androidx.appcompat.widget.AppCompatButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="黑色按钮" android:background="@color/black" />
内容的提问来源于stack exchange,提问作者M.N
相关产品推荐
相关产品推荐

