标签:
---恢复内容开始---
public View getView(int position, View convertView, ViewGroup parent) { Msg msg =getItem(position); View view; ViewHolder viewHolder; if(convertView==null){ view=LayoutInflater.from(getContext()).inflate(resourceId, null); viewHolder = new ViewHolder(); viewHolder.leftLayout=(LinearLayout)view.findViewById(R.id.left_layout); viewHolder.rigthLayout=(LinearLayout)view.findViewById(R.id.right_layout); viewHolder.leftMsg=(TextView)view.findViewById(R.id.left_msg); viewHolder.rigthMsg=(TextView)view.findViewById(R.id.right_msg); view.setTag(viewHolder); } else{ view=convertView; viewHolder=(ViewHolder)view.getTag(); } if(msg.getType()==Msg.TYPE_RECEIVED){ viewHolder.leftLayout.setVisibility(View.VISIBLE); viewHolder.rigthLayout.setVisibility(View.GONE); viewHolder.leftMsg.setText(msg.getContent()); }else if(msg.getType()==Msg.TYPE_SENT){ viewHolder.leftLayout.setVisibility(View.GONE); viewHolder.rigthLayout.setVisibility(View.VISIBLE); viewHolder.rigthMsg.setText(msg.getContent()); } return view ; } class ViewHolder{ LinearLayout leftLayout; LinearLayout rigthLayout; TextView leftMsg; TextView rigthMsg; }
---恢复内容结束---
这段代码从写了ArrayAdapter中getview方法,ViewHolder用于对控件的实例进行缓存。
其中用到了View的setTag()和getTag()方法
setTag()用于给View添加额外的数据,可以使用getTag()方法获取出这个额外的数据。
在此段代码中,我们把控件的实例都缓存在了ViewHolder中,就没有必要每次都通过findviewbyid获取实例。
标签:
原文地址:http://www.cnblogs.com/fajieyefu/p/5539487.html