Android 获取视图的当前背景id

Android 获取视图的当前背景id,android,android-layout,drawable,Android,Android Layout,Drawable,我有一个背景在drawable中定义的布局,我想在某些条件下将其更改为另一个。如何获取当前背景的标识符以了解它是什么?您好,您可以尝试此示例 btnNew =(Button)findViewById(R.id.newButton); // compare newlist if(newButton.getBackground()!=(findViewById(R.id.imgAdd)).getBackground()) { btnNew.setBackgroundResource(

我有一个背景在drawable中定义的布局,我想在某些条件下将其更改为另一个。如何获取当前背景的标识符以了解它是什么?

您好,您可以尝试此示例

btnNew =(Button)findViewById(R.id.newButton); 

 // compare newlist
if(newButton.getBackground()!=(findViewById(R.id.imgAdd)).getBackground()) 
{ 
   btnNew.setBackgroundResource(R.drawable.imgDelete); 
}

你可以这样试试

根据条件为要更改背景的布局指定id。你喜欢这样吗

            linear1 = (LinearLayout) findViewById(R.id.bg_l_l);

        if(condition==true)
        {
            linear1.setBackgroundDrawable(R.drawable.sample_thumb_0);
        }
        else if (condition2==true)
        {
            linear1.setBackgroundDrawable(R.drawable.sample_thumb_1);
        }
        else
        {
            linear1.setBackgroundDrawable(R.drawable.sample_thumb_2);
        }

只需在单击Drawalbe=view.getBackground()之前通过
Drawable即可获得整个
Drawable

并通过执行以下操作更改视图的背景:
view.setBackgroundDrawable(getResources().getDrawable(R.drawable.your_drawable))

如果你想把它设置回初始背景,你不需要id 因为您有整个可绘制的图形,所以请执行以下操作:
view.setBackgroundDrawable(单击Drawalbe之前))


就这些

这可能是一个非常古老的问题,但以防万一,如果人们仍在寻找它:

if(yourView.getBackground().getConstantState().equals(
    getResources().getDrawable(R.drawable.yourdrawable).getConstantState()){

  //do something if this is the correct drawable
}

提醒您检查空值。在某些情况下,
yourView.getBackground()
如果源是可矢量绘制的,则可以返回null。

您应该为当前布局设置
id
,然后通过
findviewbyid
在代码中声明它,然后通过此去极化,您将能够更改背景问题很有趣,但我看不到使用案例?-1 for
findViewById(R.drawable.imgAdd)
(按id查找可绘制的引用,返回null。我只是在这里写的,没有使用编辑器。无论如何,我编辑了我的答案。Thanx代表你的-1:)什么是条件,他想比较可绘制的,因为提问者告诉他,他想根据条件改变。因此,他将决定什么应该是条件。他想比较可提取的,这就是为什么他问条件谢谢你的指导。根据我对上述问题的理解,我已经回答了他。您可以根据需要进行更新。:)