What is the purpose of setTag and getTag methods in View?

Asked

Viewed 986 times

4

In the TextView declared this way below, is used the 1 as definition the attribute android:tag. Look at:

<TextView
    android:id="@+id/tvJonSnow"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:tag="1"
    android:text="Jon Snow" />

Methods are used programmatically setTag() and getTag(), thus below:

 TextView tvJonSnow = (TextView) findViewByID(R.id.tvJonSnow);
 tvJonSnow.setTag(1);

What purpose of the methods setTag() and getTag() in View? When should they be used?

2 answers

6


What purpose of setTag() and getTag methods()?

The objective of setTag() is to allow to store any object.

This object can then be recovered with getTag().

When should they be used?

When you want to associate some information to the view. It is an "easy" way to store, in the view, data related to it, instead of putting them in a separate structure.

An example is the implementation of viewholder. It uses the Listview item layout tag to store an object with references to its views.
This will allow you to obtain them without the need to repeatedly use findViewById().

setTag() and getTag() have a Overload who receives a Resource id to identify the object, allowing more than one.

To use it you must create a file in the folder res/values where declares the id’s:

xml ids.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item type="id" name="object1" />
    <item type="id" name="object2" />
    <item type="id" name="object3" />
</resources>

Note: replace objectX by any names you want.

The methods are thus used:

view.setTag(R.id.object1, object1);
view.setTag(R.id.object2, object2);
view.setTag(R.id.object3, object3);

....
....

object2 = (...)view.getTag(R.id.object2);

0

I believe that setTag() and getTag() have several functions, but in my projects I use it as follows:

Customadapter.class

    @Override
    public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {

    MyObject tema;
    private List<MyObject> items;

    customViewHolder.item.setTag(i);
    customViewHolder.item.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {

             int clickPosition = (int) v.getTag();
             tema = items.get(clickPosition);

             /*Aqui consigo pegar os items das respectivas posições, 
             sem perder a posição que está vindo no parâmetro, 
             chamando o tema.name por exemplo*/
         }
     }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.