【发布时间】:2020-04-18 08:36:01
【问题描述】:
我想有一个按钮,如果你点击它,它会设置背景,但如果背景已经设置,它会做其他事情。目前这是我的代码,但我似乎无法让它工作
if (view.background == R.drawable.frog) {
//do stuff
} else {
//other stuff
}
【问题讨论】:
标签: android button kotlin background
我想有一个按钮,如果你点击它,它会设置背景,但如果背景已经设置,它会做其他事情。目前这是我的代码,但我似乎无法让它工作
if (view.background == R.drawable.frog) {
//do stuff
} else {
//other stuff
}
【问题讨论】:
标签: android button kotlin background
您可以尝试: 使用 Kotlin:
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
}
【讨论】:
这很有帮助
val drawable = ContextCompat.getDrawable(getContext(), R.drawable.frog)
if(view.background.constantState?.equals(drawable?.constantState) == true) {
//do stuff
} else {
//other stuff
}
【讨论】:
如果它为空,则检查它是否为空,否则它未设置,否则背景已设置。
if (view.background == null) {
//do stuff
} else {
//other stuff
}
希望对你有帮助。
【讨论】: