Search code examples
androidandroid-drawable

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.drawable.B when next Button is pressed.

I defined my relative layout as follows :

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

if (rl.getBackground()== R.drawable.A){ //here the error
        rl.setBackgroundResource(R.drawable.B);
                }

The error is : incompatible operands types int and drawable. If there a way to get the current background and base on it do something?


Solution

  • 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);
    }