使用XML无法为Button添加边框,请求排查问题
Hey there! Let's dig into why your button's border isn't showing up—since the button displays and works as expected otherwise, it's almost certainly a small oversight in your styling setup. Since I can't view the screenshot content directly, here are the most common issues to check based on typical Android button border problems:
Common Fixes to Try
Double-check how you're applying the style in your main XML
Make sure you're assigning the style correctly to your Button element (likestyle="@style/button_style4") and that you aren't overriding it with anandroid:backgroundattribute set to a solid color or another drawable. If you set a direct background, it'll cover your border style entirely.Verify your
button_style4.xmldrawable structure
For a border to appear, your drawable should use a<shape>(usually rectangle) with a<stroke>tag. Common missteps here include:- Forgetting to set
android:widthon the<stroke>(if this is 0dp, the border will be invisible) - Using a border color that matches the button's background or your screen's background (so it blends in completely)
- Having a
<solid>fill that covers the stroke—if you want a solid background and a border, ensure the<stroke>is defined properly (it should sit on top of the solid fill by default, but check your order and padding if needed)
Here's a working example of a bordered button drawable for reference:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <!-- Optional solid background color --> <solid android:color="@color/white" /> <!-- Border: width and color are mandatory for visibility --> <stroke android:width="2dp" android:color="@color/blue" /> <!-- Optional rounded corners --> <corners android:radius="8dp" /> </shape>- Forgetting to set
Rule out theme conflicts
If you're using a Material Components theme, the default button styling might apply a tint that hides your custom border. Try addingandroid:backgroundTint="@null"(orapp:backgroundTint="@null"if usingMaterialButton) to your Button element to disable the default tint.Check your resource directory placement
Ensurebutton_style4.xmlis saved in theres/drawablefolder (not a version-specific folder likedrawable-v24unless you intentionally want it only for newer APIs) so it's accessible across all your app's supported devices.
If none of these resolve the issue, sharing the actual code from both your main XML layout and button_style4.xml would help pinpoint the exact problem!
内容的提问来源于stack exchange,提问作者Tim Jansen

