在 Android 8 中使用 Shape Drawable 设置 Button 的背景颜色和边框颜色
Set background color and border color of Button using Shape Drawable in Android 8
我试图在 Android 8 中使用 Shape Drawable(在 drawable 中创建 button_start.xml)设置 Button 的背景颜色和边框颜色,但它似乎不起作用。
button_start.xml 文件:
activity_main.xml 文件:
结果:
简答:.
您不需要定义背景形状,只需使用带有 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"
使用 Material 组件主题 Button
在运行时被 MaterialButton
替换,后者使用自己的 MaterialShapeDrawable
作为背景。
您可以定义自定义背景,但要避免自定义背景不着色,您必须添加 app:backgroundTint="@null"
.
2个解不等价。
使用自定义 android:background
不使用默认值 MaterialShapeDrawable
并且未设置笔划、形状外观、波纹等某些功能(因为它们与 MaterialShapeDrawable
相关)。您必须向他们提供您的自定义背景。
我试图在 Android 8 中使用 Shape Drawable(在 drawable 中创建 button_start.xml)设置 Button 的背景颜色和边框颜色,但它似乎不起作用。
button_start.xml 文件:
activity_main.xml 文件:
结果:
简答:.
您不需要定义背景形状,只需使用带有 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"
使用 Material 组件主题 Button
在运行时被 MaterialButton
替换,后者使用自己的 MaterialShapeDrawable
作为背景。
您可以定义自定义背景,但要避免自定义背景不着色,您必须添加 app:backgroundTint="@null"
.
2个解不等价。
使用自定义 android:background
不使用默认值 MaterialShapeDrawable
并且未设置笔划、形状外观、波纹等某些功能(因为它们与 MaterialShapeDrawable
相关)。您必须向他们提供您的自定义背景。