轉載請註明出處:http://blog.csdn.net/linglongxin24/article/details/52808656 【DylanAndroid的csdn博客】java
@Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; if (convertView == null) { convertView = LayoutInflater.from(context) .inflate(R.layout.item, parent, false); viewHolder = new ViewHolder(); viewHolder.name = (TextView) convertView.findViewById(R.id.name); convertView.setTag(viewHolder); }else{ viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.name.setText("sss"); return convertView; } private static class ViewHolder { TextView name; }
SparseArray(稀疏數組).他是Android內部特有的api,標準的jdk是沒有這個類的.在Android內部用來替代HashMap<Integer,E>這種形式,使用SparseArray更加節省內存空間的使用,SparseArray也是以key和value對數據進行保存的.使用的時候只須要指定value的類型便可.而且key不須要封裝成對象類型.android
/** * Created by yuandl on 2016-10-13. */ import android.util.SparseArray; import android.view.View; /** * 萬能的ViewHolder * * @author */ public class CommonViewHolder { /** * @param view 全部緩存View的根View * @param id 緩存View的惟一標識 * @return */ public static <T extends View> T get(View view, int id) { SparseArray<View> viewHolder = (SparseArray<View>) view.getTag(); //若是根view沒有用來緩存View的集合 if (viewHolder == null) { viewHolder = new SparseArray<View>(); view.setTag(viewHolder);//建立集合和根View關聯 } View chidlView = viewHolder.get(id);//獲取根View儲存在集合中的孩紙 if (chidlView == null) {//若是沒有改孩紙 //找到該孩紙 chidlView = view.findViewById(id); viewHolder.put(id, chidlView);//保存到集合 } return (T) chidlView; } }
@Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(context) .inflate(R.layout.item, parent, false); } TextView name= CommonViewHolder.get(convertView, R.id.name); name.setText("sss"); return convertView; }
--------------------- 本文來自 DylanAndroid 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/linglongxin24/article/details/52808656?utm_source=copy git