Skip to content Skip to sidebar Skip to footer

Get Current Background

I want to get the current background to do a condition base on it. For example, I have a xml with a next arrow, if the background=R.drawable.A, I want to change the background to R

Solution 1:

Actually I don't know why they didn't override the equals method in the Drawable class. So you should use getConstantState() method from the Drawable object that returns a Drawable.ConstantState instance that holds the shared state of this Drawable to be able to compare it.

Kotlin

val drawableAConstantState = ContextCompat.getDrawable(this, R.drawable.A)?.constantState
rl.setBackgroundResource(if (rl.background?.constantState == drawableAConstantState) R.drawable.B else R.drawable.A)

Java

if (rl.getBackground() != null && rl.getBackground().getConstantState().equals(getResources().getDrawable(R.drawable.A).getConstantState()) {
    rl.setBackgroundResource(R.drawable.B);
} else {
    rl.setBackgroundResource(R.drawable.A);
}

Solution 2:

You can check if the background drawable is null or not like this:

if (rl.getBackground() != null){ 
    rl.setBackgroundResource(R.drawable.B);
 }else{
 // do whatever you want
}

Solution 3:

Well to remedy the error just change it to:

final RelativeLayout rl = (RelativeLayout) findViewById(R.id.myLayout);

if (rl.getBackground() == getResources().getDrawable(R.drawable.A){ //<-- fixes the error
        rl.setBackgroundResource(R.drawable.B);
}

a side note: I suggest you check which drawable should be set against a logical component and not it's manifestation in the UI, but this is up to you.


Post a Comment for "Get Current Background"