Equivalent HTML 5 Data Attributes for Android Views

Is there a way to save / retrieve arbitrary values ​​from a view similar to HTML5 data attributes? That way, I can have generic onClick() methods to call the view, and the method can get the associated data.

eg:

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

I would like to be able to get the value from the one that was clicked.

 public void setCountry(View v){ //retrieve data somehow } 
+4
source share
2 answers

You can use the View tag property. It is intended for this purpose.

For instance:

 <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()); } 
+3
source

Derive from ImageView, add the member variable "country" and access methods. Then you can reference your class in the layout file:

 <com.foo.MyImageView ... /> 

Or use the tag property. It allows you to attach an arbitrary object to the control, but there is no type security and there are no access methods with the corresponding names. You can specify the string tag directly in the XML file.

Or use some kind of mapping from the identifier of the control to the country.

0
source

Source: https://habr.com/ru/post/1434738/


All Articles