你如何获得按钮的背景颜色?

杰森

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

 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

谁能解释我做错了什么?

加布里埃尔·马里奥蒂

由于您使用的是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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章