Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

java - 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...