Android中万能的适配器的详细讲解
在Android开发中,适配器的用处是非常大的,尤其是效率优化方面。除了使用ViewHolder复用View之外,如果存在很多的ListView或者是一个ListView中存在很多的View组件,那对代码的阅读不是很好的。考虑到优化以及共通方面,我封装了ViewHolder类以及将Adapter类封装成共通的了,将对以后的开发带来很大的方便。
适配器中提高性能优化如下:
1.利用convertView
利用Android的Recycler机制,利用convertView来重新回收View,效率有了本质提高。View的每次创建是比较耗时的,因此对于getview方法传入的convertView应充分利用 != null的判断 。
2.使用ViewHolder
ViewHolder将需要缓存的view封装好,convertView的setTag才是将这些缓存起来供下次调用。 当你的listview里布局多样化的时候 viewholder的作用体现明显,效率再一次提高。 View的findViewById()方法也是比较耗时的,因此需要考虑只调用一次,之后就用View.getTag()方法来获得ViewHolder对象。
3.优雅的使用ViewHolder
使用ViewHolder时,每次一遍一遍的findViewById,一遍一遍在ViewHolder里面添加View的定义,view一多,是不是感觉烦爆了,base-adapter-helper这个类库似乎完美的解决了这个问题。
其设计思想是使用 SparseArray来存储view的引用,代替了原本的ViewHolder,不用声明一大堆View,简洁明了。
(1).ViewHolder类的封装如下:ViewHolder类:
package com.chengdong.su.baseadapter.util;
import android.content.Context;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
* the common object of the ViewHolder
*
* @author scd
*
*/
public class ViewHolder {
/** the object of the TAG */
private String TAG = getClass().getSimpleName();
/** the object of the view */
private SparseArray<View> mViews;
/** the object of the position */
private int mPosition;
/** the object of the converview */
private View mConvertView;
/***
* 构造方法
*
* @param context
* @param parent
* @param layoutId
* @param position
*/
public ViewHolder(Context context, ViewGroup parent, int layoutId,int position) {
super();
this.mPosition = position;
this.mViews = new SparseArray<View>();
mConvertView = LayoutInflater.from(context).inflate(layoutId, parent,
false);
mConvertView.setTag(this);
}
/**
* get the object of the ViewHolder
*
* @param context
* @param convertView
* @param parent
* @param layoutId
* @param position
* @return
*/
public static ViewHolder getViewHolder(Context context, View convertView,
ViewGroup parent, int layoutId, int position) {
if (convertView == null) {
return new ViewHolder(context, parent, layoutId, position);
} else {
ViewHolder holder = (ViewHolder) convertView.getTag();
// 修改位置变化
holder.mPosition = position;
Log.d("getViewHolder", "getViewHolder:position:--->" + position);
return holder;
}
}
/**
* find the view by the viewId
*
* @param viewId
* @return
*/
@S