Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the current background id of a view

I have a Layout with a background defined in drawable, and i want to change it under some conditions to another. How do i get the identifier of the current background to know what it is?

like image 996
SnapDragon Avatar asked Nov 29 '12 08:11

SnapDragon


4 Answers

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

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

  //do something if this is the correct drawable
}

Be reminded to check for null. In some cases, yourView.getBackground() can return null if the source is vector drawable.

like image 124
Amad Yus Avatar answered Oct 31 '22 23:10

Amad Yus


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); 
}
like image 25
Talha Avatar answered Nov 01 '22 00:11

Talha


you can try by this way.

Assign id to layout which you want to change background as per 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);
        }
like image 20
Chintan Khetiya Avatar answered Nov 01 '22 00:11

Chintan Khetiya


You can simply get the whole Drawable by 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 set it back to the initial background you don't need the id because you have the whole Drawable so do: view.setBackgroundDrawable(beforeClickDrawalbe));

That's all!

like image 1
Pontios Avatar answered Nov 01 '22 00:11

Pontios