java - 动态更改材质按钮背景不起作用
问题描述
我有一个材质按钮,我想动态更改它的背景,我为此创建了可绘制的 xml,以前它可以工作,现在它不工作,我尝试了以下选项,但我的按钮仍然是蓝色的
mBtnStudy.setBackgroundResource(R.drawable.switch_left_enabled);
mBtnStudy.setBackgroundColor(getResources().getColor(R.color.red));
mBtnStudy.setBackgroundDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.switch_left_enabled));
mBtnStudy.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.switch_left_enabled));
和 xml 看起来像
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="@android:color/white"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:layout_margin="16dp">
<com.google.android.material.button.MaterialButton
android:id="@+id/btn_study"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:text="@string/study"/>
<com.google.android.material.button.MaterialButton
android:id="@+id/btn_test_yourself"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:text="@string/test_yourself"/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
可绘制
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
<!--<corners android:bottomLeftRadius="10dp" android:topLeftRadius="10dp"/>-->
<solid android:color="#bdbdbd"/>
</shape>
可能是什么问题?
解决方案
在 java 文件button.setBackgroundColor(Color.RED);
中,将 RED 替换为您想要的颜色。并使用颜色代码使用button.setBackgroundColor(Color.parseColor("#03dac5");
推荐阅读
- python - Scipy 稀疏矩阵在余弦相似度中的内存效率不高
- c - 如何指定在执行结束时执行一条指令?
- verilog - 访问具有相同代码的两个实例,而无需为每个实例重复它
- sql-server - 将兼容级别从 100 切换到 130 会导致锁定或死锁问题吗?
- javascript - 将 Lodash 的 mergeWith 与嵌套对象一起使用
- django - Django默认在数据库
- angular - Angular : Updating model doesnt work on consecutive click events
- ruby-on-rails - 使用 Phusion Passenger 5.0.30 运行 Rails 2.2.2 应用程序
- javascript - id 显示为“无法匹配任何路由。URL 段”的子路由
- java - 调整大小如何在 Java 中的 Hash Map 中工作?