如何获取按钮的背景色?

4

如何获取按钮的背景颜色?我已经尝试了以下方法:

 public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn1 = findViewById(R.id.button);
        btn1.setBackgroundColor(getResources().getColor(R.color.red));
        //color red is added to colors.xml <color name="red">#FF0000</color>

        btn1.setOnClickListener(v -> {

          ColorDrawable btnColor = (ColorDrawable) btn1.getBackground();

          int clr = btnColor.getColor();

          if (clr == getResources().getColor(R.color.red)) {
              String line = "it's red";
              btn1.setText(line);
            }
        });
    }
}

当我点击按钮时,应用程序关闭并出现以下提示。
 java.lang.ClassCastException: android.graphics.drawable.RippleDrawable cannot be cast to android.graphics.drawable.ColorDrawable

有人能解释一下我做错了什么吗?


1
请查看此链接:https://dev59.com/rGsz5IYBdhLWcg3wJUfJ - Mohammad Abdul Alim
你的应用程序中是否使用了MaterialComponents主题? - Gabriele Mariotti
@MohammadAbdulAlim 我现在会阅读,谢谢。 - jason
@GabrieleMariotti 是的,我正在使用MaterialComponents主题来设计我的应用程序,这可能是导致问题的原因吗? - jason
@jason 请查看 https://stackoverflow.com/questions/62191132/how-to-get-background-color-in-materialbutton-in-kotlin-android/62193139#62193139 - Gabriele Mariotti
3个回答

1

由于您正在使用MaterialComponents主题,因此在运行时,您的Button将被MaterialButton替换。

请使用setBackgroundTintList而不是setBackgroundColor,并使用getBackgroundTintList()检索ColorStateList

例如:

    MaterialButton button = findViewById(R.id.button);
    button.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.red600)));
    ColorStateList colorStateList = button.getBackgroundTintList();

    int defaultColor = colorStateList.getColorForState(
            new int[] { android.R.attr.state_enabled},0);

我理解这种方法是获取分配给给定状态的颜色。这在技术上与查找按钮的当前颜色不同。是否有一种编程方式可以获取控件的当前状态(而不是直接传递android.R.attr.state_enabled)? - evve

0

你可以将它作为可绘制对象获取:

Button mButton = (Button) findViewById(R.id.button);
Drawable buttonBackground = mButton.getBackground();

如果它是一种颜色,你可以这样做:

ColorDrawable btnColor = (ColorDrawable) button.getBackground();

获取颜色的资源ID:

Int color = btnColor.getColor();

然后将其与您的颜色进行比较:

if (color == R.color.green) {
   log("color is green");
}

抱歉,我对Java和Android Studio还不是很熟悉,但你发的内容不就是我已经有的吗?只不过我的代码设置了一个按钮的文本而不是输出到“日志”中,这个if语句也不一样。 - jason

-1
ColorDrawable buttonColor = (ColorDrawable) button.getBackground();
int colorId = buttonColor.getColor();
if (colorID == R.color.green) {
  log("color is green");
}

使用上述代码,您可以找到按钮的颜色。


由于某些原因,它在Android Studio上无法工作? - jason
@jason你找到任何解决方案了吗? - Suraj Pendhare

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接