未优化版本
public class ExampleAdapter extends ArrayAdapter<Example> {
int resourceId;
public ExampleAdapter(Context context, int viewResource, ArrayList<Example> data) {
super(context, viewResource, data);
resourceId = viewResource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
view = LayoutInflater.from(getContext()).inflate(resourceId, parent);
TextView mTextVIew = (TextView)view.findViewById(R.id.text_view);
Button mButton = (Button)view.findViewById(R.id.button);
return view;
}
}
1.重用convertView
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if(convertView == null) {
view = LayoutInflater.from(getContext()).inflate(resourceId,parent);
}else{
view = convertView;
}
TextView mTextVIew = (TextView)view.findViewById(R.id.text_view);
Button mButton = (Button)view.findViewById(R.id.button);
return view;
}
convertView会将之前加载好的布局进行缓存,假如convert不为null,可以直接获取view。从而减少LayoutInflater加载布局的次数。
2.使用ViewHolder
定义一个ViewHolder类,存储子View,使用SparseArray存储子View的id和其对应的View(此处使用了优化过的int-object的hashmap, 可以减少内存损耗)。使用时若不存在此子View,便创建,并存入SparseArray中。
//此处不是内部类
public class ViewHolder {
private ViewHolder(){};
public static <T extends View> T get(View view, int id) {
SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
if (viewHolder == null) {
viewHolder = new SparseArray<View>();
view.setTag(viewHolder);
}
View childView = viewHolder.get(id);
if (childView == null) {
childView = view.findViewById(id);
viewHolder.put(id, childView);
}
return (T) childView;
}
}
getView中的写法
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Thing thing = getItem(position);
View view;
if(convertView == null) {
view = LayoutInflater.from(getContext()).inflate(resourceId,parent);
}else{
view = convertView;
}
TextView mText = ViewHolder.get(View,R.id.text_view);
Button button = ViewHolder.get(View,R.id.button)
return view;
}