有没有办法可以在任何给定时间找到特定 ImageButton 设置的资源?
例如:我有一个设置为R.drawable.btn_on
onCreate 的 ImageButton。稍后,在某些时候,ImageButton 被设置为R.drawable.btn_off
. 我希望能够检查 ImageButton 在我的代码中设置的资源。
谢谢克里斯
有没有办法可以在任何给定时间找到特定 ImageButton 设置的资源?
例如:我有一个设置为R.drawable.btn_on
onCreate 的 ImageButton。稍后,在某些时候,ImageButton 被设置为R.drawable.btn_off
. 我希望能够检查 ImageButton 在我的代码中设置的资源。
谢谢克里斯
只需使用setTag()
andgetTag()
为您的ImageView
.
您可以将自己的类定义为 的子类ImageButton
,添加一个私有 int 变量并在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() 设置过。
我不知道如何直接访问资源,但是对于您尝试实现的目标,仅获取状态就足够了吗?
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 docs上的文档不正确。这里它声明pickDropPoint.getDrawableState()[android.R.attr.state_pressed]
返回true
or false
,但它返回1
or 0
, an **int**
。
我必须执行以下操作才能使其正常工作
<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);