有没有一种方法可以在任何时候找到特定ImageButton所设置的资源?
例如:我有一个ImageButton,我在onCreate中将其设置为R.drawable.btn_on
。稍后,在某个时间点,ImageButton被设置为R.drawable.btn_off。 我想能够在我的代码中检查ImageButton所设置的资源。
谢谢
Chris
有没有一种方法可以在任何时候找到特定ImageButton所设置的资源?
例如:我有一个ImageButton,我在onCreate中将其设置为R.drawable.btn_on
。稍后,在某个时间点,ImageButton被设置为R.drawable.btn_off。 我想能够在我的代码中检查ImageButton所设置的资源。
谢谢
Chris
只需使用 setTag()
和 getTag()
来关联和获取您的 ImageView
的自定义数据。
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;
}
}
我不知道如何直接访问资源,但是为了你想要实现的目标,仅获取状态是否就足够了呢?
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
Android文档上的说明是错误的。在这里它声明pickDropPoint.getDrawableState()[android.R.attr.state_pressed]
返回true
或false
,但实际上它返回一个int
类型的1
或0
。
我不得不按照以下方式才能使其正常工作。
<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 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>
whichPoint = (pickDropPoint.getDrawableState()[android.R.attr.state_pressed] > 1 ? PICKUP : DROP);