What is the main purpose of setTag() getTag() methods of View?

前端 未结 7 619
醉话见心
醉话见心 2020-11-22 01:25

What is the main purpose of such methods as setTag() and getTag() of View type objects?

Am I right in thinking that I can ass

7条回答
  •  别跟我提以往
    2020-11-22 01:54

    Setting of TAGs is really useful when you have a ListView and want to recycle/reuse the views. In that way the ListView is becoming very similar to the newer RecyclerView.

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
      {
    ViewHolder holder = null;
    
    if ( convertView == null )
    {
        /* There is no view at this position, we create a new one. 
           In this case by inflating an xml layout */
        convertView = mInflater.inflate(R.layout.listview_item, null);  
        holder = new ViewHolder();
        holder.toggleOk = (ToggleButton) convertView.findViewById( R.id.togOk );
        convertView.setTag (holder);
    }
    else
    {
        /* We recycle a View that already exists */
        holder = (ViewHolder) convertView.getTag ();
    }
    
    // Once we have a reference to the View we are returning, we set its values.
    
    // Here is where you should set the ToggleButton value for this item!!!
    
    holder.toggleOk.setChecked( mToggles.get( position ) );
    
    return convertView;
    }
    

提交回复
热议问题