首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 檢查 View 背景是否為指定 Drawable:直接比較 Drawable 物件

     編輯:程式設計綜合問答

錯誤代碼

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);
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved