Android getBackground
我试图有一个按钮,如果你点击它,它会设置背景,但如果背景已经设置好,它会做其他事情。目前这是我的代码,但我似乎无法让它工作Android getBackground,android,button,kotlin,background,Android,Button,Kotlin,Background,我试图有一个按钮,如果你点击它,它会设置背景,但如果背景已经设置好,它会做其他事情。目前这是我的代码,但我似乎无法让它工作 if (view.background == R.drawable.frog) { //do stuff } else { //other stuff } 选中null it,如果为null,则其未设置else背景已设置 if (view.background == null) { //do stuff } else {
if (view.background == R.drawable.frog) {
//do stuff
} else {
//other stuff
}
选中null it,如果为null,则其未设置else背景已设置
if (view.background == null) {
//do stuff
} else {
//other stuff
}
希望有帮助。这可能会有帮助
val drawable = ContextCompat.getDrawable(getContext(), R.drawable.frog)
if(view.background.constantState?.equals(drawable?.constantState) == true) {
//do stuff
} else {
//other stuff
}
您可以尝试:
与科特林:
val bgAlready = btnTest.background.constantState == ContextCompat.getDrawable(this, R.drawable.frog)?.constantState
if (!bgAlready) {
btnTest.background = ContextCompat.getDrawable(this, R.drawable.frog)
} else {
//other stuff
}
使用Java:
boolean bgAlready = btnTest.getBackground().getConstantState() ==
ContextCompat.getDrawable(TestActivity.this, R.drawable.frog).getConstantState();
if (!bgAlready) {
btnTest.setBackground(ContextCompat.getDrawable(TestActivity.this, R.drawable.frog));
} else {
//other stuff
}