Skip to content Skip to sidebar Skip to footer

Android:purpose Of Gettag() And Settag() In View Class

public void setTag(final Object tag) { mTag = tag; } public Object getTag() { return mTag; } These are two methods from View Class in Android. Followin

Solution 1:

Think of it as as plainly simple as it's possible - a "tag".

What does a grocery shop product tag tell you? Basically a lot of things, such as name, price, origin country, discount, and many others.

Imagine you're making an application that displays such products in a grid using ImageView's. How to easily determine the product features from the ImageView? Tagging it is one of the possible solutions.

classProduct {

    String mName;
    String mManufacturer;
    String mOriginCountry;

    double mPrice;
    int mDiscount;

    int mImageId; // A reference to a drawable item id
}

[...]

classMy Activity {

    @OverrideprotectedvoidonCreate() {
        [...] // Some code// Grab the imageView reference and grab (or create) the tag for itImageViewsomeItemView= (ImageView) findViewById(R.id.some_product_view);
        ProductsomeProductTag=newProduct( ... some data ...);

        // Add the tag to the ImageView
        someItemView.addTag(someProductTag);
    }

    privatevoiddisplayItemInfo(ImageView iv) {

        // Grab the tag and display the info.StringproductName= ((Product)iv.getTag()).mName();
        Toast.show(mContext, "This is " + productName, Toast.LONG).show(); 

    }

}

Of course this is very simplified. Ideally you would have an adapter which would create the view basing on your provided tags, or would create your tags automatically.

I hope you get the idea

Solution 2:

A good example is the View Holder pattern. An implementation can be found in this tutorial on ListViews.

The View Holder pattern allows to avoid the findViewById() method in the adapter.

A ViewHolder class is a static inner class in your adapter which holds references to the relevant views. in your layout. This reference is assigned to the row view as a tag via the setTag() method.

If we receive a convertView object, we can get the instance of the ViewHolder via the getTag() method and assign the new attributes to the views via the ViewHolder reference.

While this sounds complex this is approximately 15 % faster then using the findViewById() method.

The example

The following code shows a performance optimized adapter implementation which reuses existing views and implements the holder pattern.

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

publicclassMyPerformanceArrayAdapterextendsArrayAdapter<String> {
  privatefinal Activity context;
  privatefinal String[] names;

  staticclassViewHolder {
    public TextView text;
    public ImageView image;
  }

  publicMyPerformanceArrayAdapter(Activity context, String[] names) {
    super(context, R.layout.rowlayout, names);
    this.context = context;
    this.names = names;
  }

  @Overridepublic View getView(int position, View convertView, ViewGroup parent) {
    ViewrowView= convertView;
    // reuse viewsif (rowView == null) {
      LayoutInflaterinflater= context.getLayoutInflater();
      rowView = inflater.inflate(R.layout.rowlayout, null);
      // configure view holderViewHolderviewHolder=newViewHolder();
      viewHolder.text = (TextView) rowView.findViewById(R.id.TextView01);
      viewHolder.image = (ImageView) rowView
          .findViewById(R.id.ImageView01);
      rowView.setTag(viewHolder);
    }

    // fill dataViewHolderholder= (ViewHolder) rowView.getTag();
    Strings= names[position];
    holder.text.setText(s);
    if (s.startsWith("Windows7") || s.startsWith("iPhone")
        || s.startsWith("Solaris")) {
      holder.image.setImageResource(R.drawable.no);
    } else {
      holder.image.setImageResource(R.drawable.ok);
    }

    return rowView;
  }
} 

Solution 3:

They are just a way to attach an Object to the View. In BaseAdapter, it is used to store view ids to avoid the expensive findViewById operation each time the system request a view.

Solution 4:

The Tag field is a good way to store your own state information for any view class. One use is to store the position of a view in a ListView. See this answer for an example.

Solution 5:

setTag(int, object) is very useful for storing a custom class to a view. Here is my implementation :

 itemView.setTag(R.id.food_tag, food);

The variable food is an instance of custom object Food. The key for setTag should always be a resource id.

I could retrieve this Custom object this way in the OnClickListener():

FoodselectedFood= (Food) view.getTag(R.id.food_tag);

Post a Comment for "Android:purpose Of Gettag() And Settag() In View Class"