【发布时间】:2021-06-29 10:37:48
【问题描述】:
我正在尝试在 Android 8 中使用 Shape Drawable(在 drawable 中创建 button_start.xml)设置 Button 的背景颜色和边框颜色,但它似乎不起作用。
【问题讨论】:
标签: android xml button android-button border-color
我正在尝试在 Android 8 中使用 Shape Drawable(在 drawable 中创建 button_start.xml)设置 Button 的背景颜色和边框颜色,但它似乎不起作用。
【问题讨论】:
标签: android xml button android-button border-color
简答:。
您不需要定义背景形状,只需使用带有 shapeAppearanceOverlay 属性的MaterialButton:
<com.google.android.material.button.MaterialButton
android:layout_width="100dp"
android:layout_height="100dp"
style="@style/Widget.MaterialComponents.Button"
app:backgroundTint="@color/...."
app:strokeColor="@color/...."
app:strokeWidth="5dp"
android:padding="0dp"
android:insetLeft="0dp"
android:insetTop="0dp"
android:insetRight="0dp"
android:insetBottom="0dp"
android:text="BUTTON"
app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.MyApp.Button.Circle"
/>
与:
<style name="ShapeAppearanceOverlay.MyApp.Button.Circle" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">50%</item>
</style>
长答案:
如果你想使用背景形状,你必须添加app:backgroundTint="@null"。
比如:
<Button
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/shape_oval"
app:backgroundTint="@null"
使用材质组件主题 Button 在运行时被 MaterialButton 替换,MaterialButton 使用自己的 MaterialShapeDrawable 作为背景。
您可以定义自定义背景,但为避免自定义背景不着色,您必须添加 app:backgroundTint="@null"。
这两种解决方案不等效。
使用自定义 android:background 不使用默认 MaterialShapeDrawable 并且未设置某些功能,如笔划、形状外观、波纹(因为它们与 MaterialShapeDrawable 相关)。您必须为他们提供您的自定义背景。
【讨论】:
Button 在运行时被替换为使用自己的背景的MaterialButton。您可以定义自定义背景(但这不是最佳选择),但为避免自定义背景不着色,您必须添加 app:backgroundTint="@null"。建议您使用所有默认功能的解决方案。更多信息here