如何获取按钮的背景颜色?我已经尝试了以下方法:
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
有人能解释一下我做错了什么吗?