如何解决如何使用布局作为背景来设置按钮的背景色
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的背景颜色?
解决方法
您需要使用红色绘制另一个可绘制对象,然后使用它:
btnFoo.setBackgroundResource(R.drawable.red_drawable);
,
使用材料按钮,所有功能均已内置
<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.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....)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。