如何在Android视图中覆盖已引用样式的属性?
问题原因
- 你混用了属性命名空间:
insetLeft、insetRight是Material Components库提供的自定义属性,不属于Android原生系统属性,不能用android:前缀声明,需要使用app:前缀。 - 你将Material Button的样式挂载到了
LinearLayout控件上,而inset*系列属性是MaterialButton控件的专属属性,LinearLayout本身不识别这些属性,设置后自然不会生效。 - 补充:如果是给
MaterialButton控件设置属性时,布局中直接写的属性优先级默认高于引用样式中的同属性,只要命名空间正确就可以覆盖样式默认值。
解决方案
方案1:替换根布局为MaterialButton(适合单文本/图标+文本场景)
如果你的布局只需要展示文本+可选图标,直接使用MaterialButton作为根控件,正确设置属性即可:
<com.google.android.material.button.MaterialButton xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" style="@style/Widget.MaterialComponents.Button.TextButton" android:layout_width="match_parent" android:layout_height="wrap_content" app:insetLeft="0dp" app:insetRight="0dp" android:text="按钮文本"/>
方案2:自定义可点击LinearLayout(需要多控件组合场景)
如果必须保留两个TextView的组合布局,不要直接套用Button样式,手动配置点击效果和内边距即可:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:clickable="true" android:foreground="?attr/selectableItemBackgroundBorderless" android:orientation="horizontal" android:paddingLeft="0dp" android:paddingRight="0dp" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/serverIp" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:id="@+id/serverLastContact" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
方案3:自定义样式覆盖默认值
如果需要多处使用无左右inset的TextButton,可以自定义样式继承原生TextButton,把inset属性写在样式中:
首先在res/values/styles.xml中定义样式:
<style name="Widget.MyApp.TextButton.NoInset" parent="Widget.MaterialComponents.Button.TextButton"> <item name="insetLeft">0dp</item> <item name="insetRight">0dp</item> </style>
之后在布局中直接引用即可:
<com.google.android.material.button.MaterialButton style="@style/Widget.MyApp.TextButton.NoInset" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="按钮文本"/>
内容的提问来源于stack exchange,提问作者Dbl
相关产品推荐
相关产品推荐

