Java – The equivalent of HTML 5 data properties for Android View

The equivalent of HTML 5 data properties for Android View… here is a solution to the problem.

The equivalent of HTML 5 data properties for Android View

Is there a way to store/retrieve arbitrary values from a View, similar to HTML5 data attributes?
This way, I can get View to call the generic onClick() method, which can retrieve the relevant data.

For example:

<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 want to be able to retrieve the value from the clicked value.

public void setCountry(View v){
     retrieve data somehow
}

Solution

You can use View's tag property. It is designed for this purpose.

For example:

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

Related Problems and Solutions