Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

material design - Android Background Drawable Not Working in Button Since Android Studio 4.1

I find out that since Android Studio 4.1 I cannot change the background color of a Button by setting color on its android:background, just no effect. And custom Drawable is not working as well.

My background Drawable:

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <stroke
        android:width="1.5dp"
        android:color="@android:color/black" />

    <solid
        android:color="@android:color/white" />

    <corners
        android:radius="8dp" />

</shape>

My Button:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add To Cart"
    android:background="@drawable/background3"/>

Result:

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Android Studio 4.1 new-project wizard, for many of its templates, has the project use the Material Components for Android library. And, it sets up the default theme to be based on Theme.MaterialComponents.DayNight.DarkActionBar.

A side effect of this is that any <Button> elements in a layout get turned into MaterialButton widgets, not regular Button widgets. MaterialButton ignores android:background.

If all you want to do is to change the color, use android:backgroundTint or change the colorPrimary attribute in the theme.

If you want a button that has a custom background, and your theme is set up to use Theme.MaterialComponents, you could switch the XML element in the layout to be <android.widget.Button> instead of <Button>. This should cause the Material Components for Android to ignore that element, and you can manipulate this button normally with respect to XML attributes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...