ベースBaseAdapterクラスをカプセル化
8387 ワード
public abstract class MyBaseAdapter<T> extends BaseAdapter {
private List<T> data;
private LayoutInflater inflater;
private int layoutRes;
public MyBaseAdapter(Context context, int layoutRes, List<T> data) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.layoutRes = layoutRes;
if (data == null) {
this.data = new ArrayList<>();
} else {
this.data = data;
}
}
public void updateRes(List<T> data) {
// this.data.clear();
// this.data.addAll(data);
this.data = data;
notifyDataSetChanged();
}
public void removeRes(int position) {
data.remove(position);
notifyDataSetChanged();
}
public void adddateRes(List<T> data) {
if (data != null && data.size() > 0) {
this.data.addAll(data);
notifyDataSetChanged();
}
}
public int getCount() {
return data != null ? data.size() : 0;
}
public T getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(layoutRes, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
bindData(position, holder, getItem(position));
return convertView;
}
public abstract void bindData(int position, ViewHolder holder, T t);
protected static class ViewHolder {
public View layout;
private Map, View> cacheView;
public ViewHolder(View convertView) {
layout = convertView;
cacheView = new HashMap<>();
}
public View getView(int resId) {
View view = null;
if (cacheView.containsKey(resId)) {
view = cacheView.get(resId);
} else {
view = layout.findViewById(resId);
cacheView.put(resId, view);
}
return view;
}
}
}