比较按钮的背景资源

7
button.setBackgroundResource(R.Drawable.abc);
if ( button.getBackground()==getResources().getDrawable(R.drawable.abc))
{
    button.setBackgroundResource(R.drawable.xyz);
}

else if( button.getBackground()==getResources().getDrawable(R.drawable.xyz) )
{
    button.setBackgroundResource(R.drawable.abc);
}

我想比较设置在按钮上的背景图片。上面的代码来自Stack Overflow...但似乎不起作用。
请建议更好的方法。
1个回答

22

试试这个

if ( button.getBackground().getConstantState()==getResources().getDrawable(R.drawable.abc).getConstantState())
{
     button.setBackgroundResource(R.drawable.xyz);
}

2
尽管Android Studio没有对此提出异议,但这种方法最近并没有奏效。也许“正确”的方法已经有所改变?我已经尝试了问题中的方法和答案中的方法。 - Dmitriy Fialkovskiy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接