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?
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.
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);
}
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);
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With