![](/img/trans.png)
[英]Android: Unable to change background (drawable) of a button in Fragment
[英]Comparing background of a button to a drawable (Android)
我试图将按钮的背景与这样的可绘制资源进行比较:
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());
}
但它总是 go 到else
语句。 它是由单击按钮触发的,即使背景是bg_default_note_button
它也会转到else
。
日志:(当drawable是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
使用“==”比较 Drawables/Bitmap 只是通过比较它们的“指向内存的指针”(这不是真的,但考虑一下)而不是它们的像素来完成。 因此,当您从 getResources() 加载 Drawable 时,会创建一个新的 object,因此这个新的 object 总是具有与第一个不同的 memory 指针。
最快的方法是只使用“getResource().getDrawable()”加载背景一次,并将结果分配给 memory 中的 PERSISTENT VARIABLE。 当您需要(第一次......)为按钮分配背景时,您可以使用该持久变量。 这样,“==”比较(我更喜欢“.equals()”)将返回 TRUE,因为两者都是完全相同的对象。
如果您打算更改按钮背景的单个像素,那么此解决方案不适合您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.