近期在做项目时,又要写 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(Context context, int layoutId) { super(); this.views = new SparseArray<View>(); this.convertView = View.inflate(context, layoutId, null); convertView.setTag(this); } /** * 获取 holder * * @param context * @param convertView getView 的 convertView * @param layoutId item View 的 布局文件 id * @return */ public static ViewHolder2 getHolder(Context context, View convertView,int layoutId) { if (convertView.getTag() == null) { return new ViewHolder2(context, layoutId); } 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 getConvertView() { return convertView; } }
用法:
public View getView(int position, View convertView, ViewGroup parent) { ViewHolder mViewHolder = ViewHolder.get(context,convertView,layoutId); TextView price = mViewHolder.getView(R.id.price); // ...其它getView return mViewHolder.getConvertView(); }
当中第一篇文章还分享了一个框架:
临时没时间研究,有兴趣的同学能够看一下!
从事Android开发不久。有问题,希望大家留言交流,共同成长!
时间: 2024-10-12 23:56:12