Android ImageButton - 确定当前设置的资源是什么

10

有没有一种方法可以在任何时候找到特定ImageButton所设置的资源?

例如:我有一个ImageButton,我在onCreate中将其设置为R.drawable.btn_on。稍后,在某个时间点,ImageButton被设置为R.drawable.btn_off。 我想能够在我的代码中检查ImageButton所设置的资源。

谢谢 Chris

4个回答

14

只需使用 setTag()getTag() 来关联和获取您的 ImageView 的自定义数据。


3
您可以将自己的类定义为ImageButton的子类,添加一个私有整型变量,并在调用setImageResource(int)时进行设置。例如:
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;
    }
}

我没有测试过,但你应该能理解 - 然后你可以在你的按钮上调用getImageResource(),假设它之前已经使用setImageResource()进行了设置。

话虽如此,我同意slup的观点 - 如果你想测试按钮的状态,有更合乎逻辑的方法来做。 - Joubarc

0

我不知道如何直接访问资源,但是为了你想要实现的目标,仅获取状态是否就足够了呢?

    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


0

Android文档上的说明是错误的。在这里它声明pickDropPoint.getDrawableState()[android.R.attr.state_pressed]返回truefalse,但实际上它返回一个int类型的10

我不得不按照以下方式才能使其正常工作。

            <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" />

按下感的可绘制XML
<?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>

在代码中,你不需要像@slup建议的那样使用for循环。
whichPoint = (pickDropPoint.getDrawableState()[android.R.attr.state_pressed] > 1 ? PICKUP : DROP);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接