Getting current background id in view

I have a layout with the background defined in drawable, and I want to change it in some conditions to another. How to get the identifier of the current background to find out what it is?

+4
source share
4 answers

This may be a very old question, but just in case, if people are still looking for it:

if(yourView.getBackground().getConstantState().equals( getResources().getDrawable(R.drawable.yourdrawable).getConstantState()){ //do something if this is the correct drawable } 
+5
source

Hi, you can try this example,

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

you can try this way.

Assign an identifier to the layout that you want to change the background to match the condition. and do like this

  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); } 
+1
source

You can just get the Drawable integer on Drawable beforeClickDrawalbe=view.getBackground();

and change the background of your view by doing: view.setBackgroundDrawable(getResources().getDrawable(R.drawable.YOUR_DRAWABLE));

and then, if you want to return it to its original background, you do not need an identifier because you have the whole Drawable like this: view.setBackgroundDrawable(beforeClickDrawalbe));

What all!

+1
source

All Articles