简体   繁体   中英

Comparing background of a button to a drawable (Android)

im trying to compare the background of a button to a drawable resource like this:

if (selectedButton.getBackground().getConstantState()
==getResources().getDrawable(R.drawable.bg_default_note_button).getConstantState()){
                            
    selectedButton.setBackgroundResource(R.drawable.bg_selected_note_button);
else{
    Log.d("1",selectedButton.getBackground().getConstantState.toString());
    Log.d("2",getResources().getDrawable(R.drawable.bg_default_note_button).getConstantState.toString());

}

but it will always go to else statement. it is triggered by a button click and even when the background is bg_default_note_button it goes to else .

the log:(when drawable is bg_default_note_button

2020-12-30 11:15:08.958 8952-8952/com.example.weekplanner D/1: android.graphics.drawable.StateListDrawable@af66108
2020-12-30 11:15:08.958 8952-8952/com.example.weekplanner D/2: android.graphics.drawable.StateListDrawable@760a287

Comparison of Drawables/Bitmap using "==" is done just by comparing their "pointers to memory" (it's not really true, but consider as it) and not their pixels. So when you load Drawable from getResources() a new object is created so this new object has ALWAYS different memory pointer then the first one.

Fastest way is to load the background using "getResource().getDrawable()" only once and assign the result to a PERSISTENT VARIABLE in memory. When you need to assign (first time..) a background for the button you can use that persistent variable. In this way an "==" comparison (I would prefer ".equals()") will returns TRUE because both are same EXACTLY object.

If you intend to change even a single pixel of button's background, then this solution is not usable for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM