views:

77

answers:

3

Is there a way I can find what resource a particular ImageButton is set to, at any given time?

For eg: I have an ImageButton that I set to R.drawable.btn_on onCreate. Later, at some point, the ImageButton gets set to R.drawable.btn_off. I want to be able to check what resource the ImageButton is set to in my code.

Thanks Chris

+1  A: 

I don't know how to access the resource directly, but for what you try to achieve, wouldn't it suffice to just get the state?

    ImageButton btn = (ImageButton) findViewById(R.id.btn);

    int [] states = btn.getDrawableState();
    for (int i : states) {
        if (i == android.R.attr.state_pressed) {
            Log.v("btn", "Button in pressed state");
        }
    }

http://developer.android.com/reference/android/R.attr.html#state_pressed

slup
A: 

You could define your own class as a child of ImageButton, add a private int variable and set it when setImageResource(int) is called. Something like:

public class MyImageButton extends ImageButton {

    private int mImageResource = 0;

    @Override
    public void setImageResource (int resId) {
        mImageResource = resId;
        super.setImageResource(resId);
    }

    public int getImageResource() {
        return mImageResource;
    }
}

I didn't test it, but you get the idea - then you can call getImageResource() on your button, assuming it has been previously set with setImageResource().

Joubarc
That said, I agree with slup - if you want to test the state of your button, there are more logical ways to do it.
Joubarc
+1  A: 

Just use setTag() and getTag() to associate and retrieve custom data for your ImageView.

CommonsWare
Thanks, I learned something too. Seems way easier indeed.
Joubarc