如何使用布局作为背景设置按钮的背景颜色

How to set the background color of a button using a layout as the background

layout_bg.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF"/>
    <!--<stroke android:width="3dp" android:color="#B1BCBE" />-->
    <corners android:radius="10dp"/>
    <padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" />
</shape>

main_activity.xml

<ImageButton
            android:background="@drawable/layout_bg"
            android:src="@drawable/myicon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:tint="@android:color/black"
            android:minWidth="80.0dp"
            android:minHeight="80.0dp"
            android:padding="10px"
            android:scaleType="fitCenter"
            android:layout_alignParentBottom="true"
            android:id="@+id/btnFoo"
            android:layout_marginLeft="91.0dp" 
           />

我正在将我的 ImageButton 的背景设置为一个布局,这样我就可以拥有动态圆角,正如您在这张图片中看到的那样:

但是,我需要将该按钮的背景颜色更改为另一种纯色,例如红色。

如果我用btnFoo.SetBackgroundColor(Color.Red)设置背景颜色,那么圆角就没有了。

我假设是因为它将背景属性覆盖为纯色值而不是 layout_bg.xml 文件。

如何设置这个特定 ImageButton 的背景颜色,而不是 main_activity 中使用 layout_bg 作为背景的所有 ImageButton 的背景颜色?

使用 material 按钮,所有功能都已内置

    <com.google.android.material.button.MaterialButton
              android:layout_width="size"
              android:layout_height="size"
              android:backgroundTint="@color/colorPrimary"
              android:text="Add Images"
              android:textAllCaps="false"
              android:textColor="@color/white"
              app:cornerRadius="20dp"
              android:layout_marginRight="10dp"
              android:layout_marginLeft="20dp"/>

您需要制作另一个红色的可绘制对象然后使用它:

btnFoo.setBackgroundResource(R.drawable.red_drawable);

您可以使用类似的东西:

    btnFoo.background.colorFilter =
        BlendModeColorFilterCompat.createBlendModeColorFilterCompat(
            color, BlendModeCompat.SRC_ATOP)

注:需要androidx.core:core:1.2.0

作为替代,您可以使用 MaterialButton :

   <com.google.android.material.button.MaterialButton
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:insetTop="0dp"
        android:insetBottom="0dp"
        app:icon="@drawable/ic_add_24px"
        app:iconGravity="textStart"
        app:iconPadding="0dp"
        app:iconSize="48dp"
        android:backgroundTint="@color/..."
        android:textColor="#FFFFFF"
        app:cornerRadius="10dp"/>

在这种情况下只需使用:

button1.backgroundTintList = ContextCompat.getColorStateList(this, R.color....)