自Android Studio 4.1起,Android Background Drawable在按钮中不起作用 [英] Android Background Drawable Not Working in Button Since Android Studio 4.1
问题描述
我发现,自Android Studio 4.1起,我无法通过在 android:background
上设置颜色来更改 Button
的背景颜色,但没有任何效果.而且自定义 Drawable
不能正常工作.
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"/>
结果:
推荐答案
对于许多模板,Android Studio 4.1新建项目向导的项目都使用Android的材料组件库.并且,它将默认主题设置为基于 Theme.MaterialComponents.DayNight.DarkActionBar
.
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
.
此方法的副作用是,布局中的任何< Button>
元素都会变成 MaterialButton
小部件,而不是常规的 Button
小部件. MaterialButton
会忽略 android:background
.
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
.
如果您只想更改颜色,请使用 android:backgroundTint
或更改主题中的 colorPrimary
属性.
If all you want to do is to change the color, use android:backgroundTint
or change the colorPrimary
attribute in the theme.
如果您想要一个具有自定义背景的按钮,并且将和主题设置为使用 Theme.MaterialComponents
,则可以将布局中的XML元素切换为是< android.widget.Button>
而不是< Button>
.这将导致Android的Material Components忽略该元素,并且您可以相对于XML属性正常操作此按钮.
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.
这篇关于自Android Studio 4.1起,Android Background Drawable在按钮中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!