有没有一种方法可以从 View 中存储/检索任意值,类似于 HTML5 数据属性?
这样,我可以让 View 调用通用 onClick()
方法,该方法可以检索相关数据。
例如:
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="setCountry"
android:src="@drawable/ic_flag_germany" />
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="setCountry"
android:src="@drawable/ic_flag_france" />
...
我希望能够从被点击的值中检索值。
public void setCountry(View v){
//retrieve data somehow
}
最佳答案
您可以使用View
的tag属性(property)。它就是为此目的而设计的。
例如:
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="setCountry"
android:src="@drawable/ic_flag_germany"
android:tag="Germany" />
...
public void setCountry(View v) {
System.out.println(v.getTag());
}
关于java - Android View 的 HTML 5 数据属性的等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12469473/