未優(yōu)化版本
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會(huì)將之前加載好的布局進(jìn)行緩存,假如convert不為null丁屎,可以直接獲取view。從而減少LayoutInflater加載布局的次數(shù)。
2.使用ViewHolder
定義一個(gè)ViewHolder類矩桂,存儲(chǔ)子View,使用SparseArray存儲(chǔ)子View的id和其對(duì)應(yīng)的View(此處使用了優(yōu)化過(guò)的int-object的hashmap, 可以減少內(nèi)存損耗)。使用時(shí)若不存在此子View痪伦,便創(chuàng)建侄榴,并存入SparseArray中。
//此處不是內(nèi)部類
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;
}