原網(wǎng)址:http://www.cnblogs.com/prescheng/p/5002708.html
相當(dāng)于iOS 的dataSource吧!
ViewHolder通常出現(xiàn)在適配器里,為的是listview滾動的時候快速設(shè)置值,而不必每次都重新創(chuàng)建很多對象,從而提升性能。
在android開發(fā)中Listview是一個很重要的組件,它以列表的形式根據(jù)數(shù)據(jù)的長自適應(yīng)展示具體內(nèi)容,用戶可以自由的定義listview每一列的布局,但當(dāng)listview有大量的數(shù)據(jù)需要加載的時候,會占據(jù)大量內(nèi)存,影響性能,這時候就需要按需填充并重新使用view來減少對象的創(chuàng)建。
ListView加載數(shù)據(jù)都是在public View getView(int position, View convertView,?ViewGroup parent)?{}方法中進(jìn)行的
(要自定義listview都需要重寫listadapter:如BaseAdapter,SimpleAdapter,CursorAdapter的等的getvView方法),
優(yōu)化listview的加載速度就要讓convertView匹配列表類型,并最大程度上的重新使用convertView。
getview的加載方法一般有以下三種種方式:
1.每一次都重新定義一個View載入布局,再加載數(shù)據(jù)(最慢的加載方式)
public View getView(int position, View convertView, ViewGroup parent)
{
View view = LayoutInflater.from(context).inflate(R.layout.main_item,null);
? ? ? ? ? ? ImageView imageView = (ImageView)convertView.findViewById(R.id.item_img);
? ? ? ? ? ? TextView textView = (TextView)convertView.findViewById(R.id.item_txt);
? ? ? ? imageView.setBackgroundResource(imgs[position]);
? ? ? ? textView.setText(strs[position]);
? ? ? ? return view;
}
2.當(dāng)convertView不為空的時候直接重新使用convertView從而減少了很多不必要的View的創(chuàng)建,然后加載數(shù)據(jù)(正常的加載方式)
public View getView(int position, View convertView, ViewGroup parent)
{
if(convertView = null){
convertView = LayoutInflater.from(context).inflate(R.layout.main_item,null);
? ? ? ? ? ? }
? ? ? ? ImageView imageView = (ImageView)convertView.findViewById(R.id.item_img);
? ? ? ? TextView textView = (TextView)convertView.findViewById(R.id.item_txt);
? ? ? ? imageView.setBackgroundResource(imgs[position]);
? ? ? ? textView.setText(strs[position]);
? ? ? ? return convertView;
}
3.定義一個ViewHolder,將convetView的tag設(shè)置為ViewHolder,不為空時重新使用即可(最快的加載方式)
class ViewHolder{
? ? ? ? ImageView imageView;
? ? ? ? TextView textView;
? ? }publicView getView(int position, View convertView, ViewGroup parent) {
? ? ? ? ViewHolder holder;
? ? ? ? if(convertView ==null){
? ? ? ? ? ? convertView = LayoutInflater.from(context).inflate(R.layout.main_item,parent,false);
? ? ? ? ? ? holder =new ViewHolder();
? ? ? ? ? ? holder.imageView = (ImageView)convertView.findViewById(R.id.item_img);
? ? ? ? ? ? holder.textView = (TextView)convertView.findViewById(R.id.item_txt);
? ? ? ? ? ? convertView.setTag(holder);
? ? ? ? }else {
? ? ? ? ? ? holder = (ViewHolder)convertView.getTag();
? ? ? ? }
? ? ? ? holder.imageView.setBackgroundResource(imgs[position]);
? ? ? ? holder.textView.setText(strs[position]);
? ? ? ? return convertView;
? ? }