【问题标题】:Dynamically change Material Button background not working [duplicate]动态更改材质按钮背景不起作用[重复]
【发布时间】:2020-03-16 09:14:55
【问题描述】:

我有一个 Material 按钮,我想动态更改它的背景,我为此创建了可绘制的 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>

可能是什么问题?

【问题讨论】:

  • 将此添加到您的视图应用程序:backgroundTint="@null"

标签: java android android-layout


【解决方案1】:

在java文件button.setBackgroundColor(Color.RED); 将红色替换为您想要的颜色。 并使用颜色代码使用button.setBackgroundColor(Color.parseColor("#03dac5");

【讨论】:

  • 它不起作用,我已经尝试过了,我在问题中提到过,我不知道我错过了什么,经过很长时间我在 android 上工作,这些天我在 Flutter 上工作
  • 尝试将 android:clickable=true 添加到按钮@sagar
猜你喜欢
  • 1970-01-01
  • 2014-08-03
  • 2016-11-28
  • 1970-01-01
  • 2018-09-06
  • 2017-05-10
  • 2020-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多