首页 > 解决方案 > MaterialComponents 中 android:background 的替代方法是什么?

问题描述

问题:android:background 在 MaterialComponents 中没有生效。

在我的项目中,我使用的是 AppCompat

( <style name="DayTheme" parent="Theme.AppCompat.Light.NoActionBar">) 一切正常。但是,由于我的项目中有一些要求,现在,我必须使用 MaterialComponents

( <style name="DayTheme" parent="Theme.MaterialComponents.Light.NoActionBar">)

正因为如此,一些 UI 看起来很糟糕。

问题:在 AppComapt 中,我使用 android:background="@drawable/bg_circle_btn"的效果很好,但在 MaterialComponents 中,这个背景没有生效。

我试图改变颜色,所有形状,但它没有产生效果。

 <Button
                                android:id="@+id/custom_category_image"
                                android:layout_width="match_parent"
                                android:layout_height="25dp"
                                android:layout_alignParentTop="true"
                                android:layout_centerHorizontal="true"
                                android:background="@drawable/bg_circle_btn"
                                android:text="A"
                                android:textColor="@color/colorWhite"
                                android:textSize="12dp"
                                android:visibility="gone"
                                app:srcCompat="@drawable/ic_navigate_next_black_24dp" />

(我使用的是按钮,因为不是任何固定的图像,而是我在这个按钮中设置标题的第一个字母,这个按钮实际上是在 carview 里面,所以它也是 cirlce。)

bg_circle_btn:

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

    <solid android:color="?attr/toolbarcolor" />

    <size
        android:width="120dp"
        android:height="120dp" />
</shape>

请注意,在整个项目中,我需要使用这个背景,所以请不要提供任何其他替代方式。

标签: androidandroid-buttonmaterial-components-androidmaterial-components

解决方案


您可以使用androidx.appcompat.widget.AppCompatButton而不是Button. 这将解决您的问题。

除此之外,您可以使用android:backgroundTint仅更改颜色。

要同时更改 ( Shape&Color ) com.google.android.material.button.MaterialButton,您必须从您的代码中执行此操作:

setBackgroundResource(R.drawable.bg_circle_btn) setBackgroundTintList(ColorStateList.valueOf(Color.RED))


推荐阅读