你如何获得按钮的背景颜色?我尝试了以下方法:
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);
关于java - 你如何获得按钮的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67663637/