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

4

In% with% declared in this way below, the TextView is used as the definition of the 1 attribute. See:

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

Programmatically the android:tag and setTag() methods are used, as follows:

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

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

    
asked by anonymous 27.06.2017 / 16:52

2 answers

6
  

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

The purpose of setTag() is to allow saving any object.

This object can then be retrieved with getTag() .

  

At what time should they be used?

When you want to associate some information with the view. It is an "easy" way to store data in the view, rather than putting it in a separate structure.

One example is the implementation of the default ViewHolder . In it, the ListView item layout tag is used to store an object with references to its views. This will allow you to get them, without the need to repeatedly use findViewById() .

setTag () and < a overload that gets a overload resource id to identify the object, allowing to save more than one.

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

ids.xml

<?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 with the names you want.

The methods are used like this:

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

....
....

object2 = (...)view.getTag(R.id.object2);
    
27.06.2017 / 17:02
0

I believe that setTag () and getTag () have several functions, but in my projects I use the following form:

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*/
         }
     }
    
27.06.2017 / 17:00