【发布时间】:2021-08-12 06:15:57
【问题描述】:
如何获得按钮的背景颜色?我尝试了以下方法:
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
谁能解释我做错了什么?
【问题讨论】:
-
检查this
-
您是否在应用中使用 MaterialComponents 主题?
-
@MohammadAbdulAlim 我现在读一读,谢谢。
-
@GabrieleMariotti 是的,我在我的应用程序中使用了 MaterialComponents 主题,这是导致问题的原因吗?
-
@jason Check stackoverflow.com/questions/62191132/…
标签: java android android-drawable android-button rippledrawable