錯誤代碼
Drawable d = v1.getBackground();
if (d.getConstantState() == getResources().getDrawable(R.drawable.correct_ans_back)) {
// 編譯錯誤:ConstantState vs Drawable 類型不匹配
}
正確比較方式
Drawable target = getResources().getDrawable(R.drawable.correct_ans_back);
Drawable current = v1.getBackground();
// 方式一:比較 ConstantState(推薦,忽略 Mutable 狀態)
if (current != null && current.getConstantState().equals(target.getConstantState())) {
// 背景匹配
}
// 方式二:直接比較 Drawable 實例(僅同一實例才 true)
if (current == target) { ... }
關鍵差異
| 比較方式 | 適用場景 |
getConstantState().equals() | 從同一資源載入的 Drawable,即使是不同實例也視為相等 |
== | 必須是完全同一物件實例 |
完整範例
View v = findViewById(R.id.my_view);
Drawable expected = ContextCompat.getDrawable(this, R.drawable.correct_ans_back);
Drawable actual = v.getBackground();
if (actual != null && actual.getConstantState() != null
&& actual.getConstantState().equals(expected.getConstantState())) {
v.setBackgroundResource(R.drawable.a);
} else {
v.setBackgroundResource(R.drawable.b);
}