Android ImageButton - determine what resource is currently set

微笑、不失礼 提交于 2019-11-29 09:42:39

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

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().

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

The documentation on android docs is incorrect. Here it states that pickDropPoint.getDrawableState()[android.R.attr.state_pressed] returns true or false, but instead it returns 1 or 0, an **int**.

I had to do the following to get it working

            <ImageButton
            android:id="@+id/pickDropPoint"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="6"
            android:background="#EEeeeee4"
            android:contentDescription="pick or drop point"
            android:src="@drawable/pickupdrop" />

The drawable xml for pressed feel

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:src="@drawable/start32" android:state_pressed="true"/>
    <item android:src="@drawable/end32" android:state_pressed="false"/>
    <corners
        android:bottomLeftRadius="3dp"
        android:bottomRightRadius="3dp"
        android:topLeftRadius="3dp"
        android:topRightRadius="3dp" />

</selector>

In code, you dont need the for loop as suggested by @slup

whichPoint = (pickDropPoint.getDrawableState()[android.R.attr.state_pressed] > 1 ? PICKUP : DROP);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!