Android中MaterialButton(OutlinedButton样式)背景色修改求助
嘿,我来帮你搞定这个按钮背景色的问题!你现在用的是Widget.MaterialComponents.Button.OutlinedButton样式,默认情况下这个轮廓按钮的背景是透明的,但因为你的主题里colorPrimary设为了橙色,导致按钮继承了这个颜色作为背景。要改成白色其实很简单,关键要知道MaterialButton的背景色是由app:backgroundTint属性控制的,而非传统的android:background。
下面给你两种可行的解决方案:
方案一:直接在XML按钮标签中设置
直接给你的MaterialButton添加app:backgroundTint="@android:color/white"属性,就能覆盖主题带来的橙色背景。修改后的完整XML代码如下:
<com.google.android.material.button.MaterialButton android:id="@+id/btnWatchVideo" style="@style/Widget.MaterialComponents.Button.OutlinedButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="@string/watch_video" android:textColor="@color/colorBlack" android:visibility="visible" app:backgroundTint="@android:color/white" app:strokeColor="@color/colorBlack" app:strokeWidth="2dp" />
方案二:自定义样式统一修改
如果你有多个类似的按钮需要设置白色背景,可以自定义一个继承自原轮廓按钮样式的新样式,方便统一管理:
- 在
styles.xml中添加自定义样式:
<style name="WhiteBackgroundOutlinedButton" parent="Widget.MaterialComponents.Button.OutlinedButton"> <item name="backgroundTint">@android:color/white</item> </style>
- 在按钮中使用这个新样式:
<com.google.android.material.button.MaterialButton android:id="@+id/btnWatchVideo" style="@style/WhiteBackgroundOutlinedButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="@string/watch_video" android:textColor="@color/colorBlack" android:visibility="visible" app:strokeColor="@color/colorBlack" app:strokeWidth="2dp" />
补充说明
你使用的com.google.android.material:material:1.2.1版本完全支持backgroundTint属性,而且你的主题已经是Theme.MaterialComponents.Light.NoActionBar,符合Material组件的使用要求,所以这两种方案都能正常生效。
内容的提问来源于stack exchange,提问作者RaJ
相关产品推荐
相关产品推荐

