标签:android 框架 viewholder
最近在做项目时,又要写 ViewHolder,
突然想到网上看看有没什么好的写法!
不知道你是不是也烦透了写那些没有技术含量的ViewHolder
看看这些,或许会有收获!
然后就找到了下面两篇文章(感谢分享!):
然后自己整理的了, 保存起来,省的忘记,顺便分享一下!
第二种 优雅写法中有一点点小问题,应该是作者粗心!
直接贴代码了:
第一种:
import android.util.SparseArray; import android.view.View; /** * ViewHolder 的通用写法 * * 来自 : http://www.eoeandroid.com/thread-321547-1-1.html * * @author LiuJinpeng * */ public class ViewHolder { private ViewHolder() {} @SuppressWarnings("unchecked") public static <T extends View>T getChildView(View convertView,int id) { SparseArray<View> viewHolder = (SparseArray<View>) convertView.getTag(); if (viewHolder == null) { viewHolder = new SparseArray<View>(); convertView.setTag(viewHolder); } View childView = viewHolder.get(id); if (childView == null) { childView = convertView.findViewById(id); viewHolder.put(id, childView); } return (T) childView; } }
@Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(context) .inflate(R.layout.banana_phone, parent, false); } ImageView bananaView = ViewHolder.get(convertView, R.id.banana); TextView phoneView = ViewHolder.get(convertView, R.id.phone); BananaPhone bananaPhone = getItem(position); phoneView.setText(bananaPhone.getPhone()); bananaView.setImageResource(bananaPhone.getBanana()); return convertView; }
第二种:
import android.util.SparseArray; import android.view.View; /** * ViewHolder 优雅写法 * * 来自:http://stackvoid.com/using-adapter-in-efficiency-way/ * * @author LiuJinpeng * */ public class ViewHolder2 { private final SparseArray<View> views; private View convertView; private ViewHolder2(View convertView) { super(); this.views = new SparseArray<View>(); this.convertView = convertView; convertView.setTag(this); } public static ViewHolder2 getHolder(View convertView) { if (convertView.getTag() == null) {<span style="white-space:pre"> </span>//这里应该是作者粗心写错了,如果查看的是原文章记得修改 return new ViewHolder2(convertView); } return (ViewHolder2) convertView.getTag(); } @SuppressWarnings("unchecked") public <T extends View>T getChildView(int viewId) { View childView = views.get(viewId); if (childView == null) { childView = convertView.findViewById(viewId); views.put(viewId, childView); } return (T) childView; } }
public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(context).inflate( R.layout.good_list_item, null, false); } ViewHolder mViewHolder = ViewHolder.get(convertView); TextView price = mViewHolder.getView(R.id.price); // ...其他getView return convertView; }
暂时没时间研究,有兴趣的同学可以看一下!
从事Android开发不久,有问题,希望大家留言交流,共同成长!
标签:android 框架 viewholder
原文地址:http://blog.csdn.net/jingdoudou56/article/details/44803103