Android中android:background属性无法在按钮上正常生效的解决方案求助
Hey there! Let's work through this frustrating button styling issue you're dealing with. The core problem here is that modern Android projects use MaterialButton as the default implementation for the <Button> tag, and Material Design components override the android:background attribute with their own built-in tinting system. That's why only your rounded corners showed up, while the default purple background and custom border didn't take effect.
Here's a straightforward, efficient solution:
Step 1: Use MaterialButton Explicitly and Disable Default Background Tint
Update your layout to use MaterialButton directly, and add app:backgroundTint="@null" to turn off the default tint that's overriding your custom drawable. This lets your round_button drawable take full control of the button's appearance.
Modified activity_main.xml Code:
<com.google.android.material.button.MaterialButton android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:background="@drawable/round_button" app:backgroundTint="@null" <!-- This line fixes the override issue --> app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
Step 2: Keep Your Existing round_button.xml Drawable
Your custom shape drawable is already correctly configured—no changes needed here:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <solid android:color="@color/black" /> <stroke android:width="3dp" android:color="@color/teal_200" /> <corners android:radius="25dp" /> </shape>
Why This Works
MaterialButtonuses aMaterialShapeDrawableby default, which applies your theme's accent color (that persistent purple you saw) via thebackgroundTintproperty. Settingapp:backgroundTint="@null"disables this default behavior.- With the tint turned off, your custom
shapedrawable is applied fully—including the solid black background, teal border, and rounded corners.
Bonus: Reusable Style Option
If you want to apply this styling to multiple buttons, create a custom style in themes.xml:
<style name="CustomRoundedButton" parent="Widget.MaterialComponents.Button"> <item name="backgroundTint">@null</item> <item name="android:background">@drawable/round_button</item> </style>
Then apply it to your button with style="@style/CustomRoundedButton".
This should give you exactly the custom bordered rounded button you're expecting!
内容的提问来源于stack exchange,提问作者Shafique Ahmed

