Skip to content

Instantly share code, notes, and snippets.

@NLMartian
Created September 16, 2014 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NLMartian/a525886bcde7892174a9 to your computer and use it in GitHub Desktop.
Save NLMartian/a525886bcde7892174a9 to your computer and use it in GitHub Desktop.
SimpleBaseAdapter
public abstract class SimpleBaseAdapter<T> extends BaseAdapter {
protected Context context;
protected List<T> data;
public SimpleBaseAdapter(Context context, List<T> data) {
this.context = context;
this.data = data == null ? new ArrayList<T>() : new ArrayList<T>(data);
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
if (position >= data.size())
return null;
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
/**
* 该方法需要子类实现,需要返回item布局的resource id
*
* @return
*/
public abstract int getItemResource();
/**
* 使用该getItemView方法替换原来的getView方法,需要子类实现
*
* @param position
* @param convertView
* @param parent
* @param holder
* @return
*/
public abstract View getItemView(int position, View convertView, ViewHolder holder);
@SuppressWarnings("unchecked")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (null == convertView) {
convertView = View.inflate(context, getItemResource(), null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return getItemView(position, convertView, holder);
}
public class ViewHolder {
private SparseArray<View> views = new SparseArray<View>();
private View convertView;
public ViewHolder(View convertView) {
this.convertView = convertView;
}
@SuppressWarnings("unchecked")
public <T extends View> T getView(int resId) {
View v = views.get(resId);
if (null == v) {
v = convertView.findViewById(resId);
views.put(resId, v);
}
return (T) v;
}
}
public void addAll(List<T> elem) {
data.addAll(elem);
notifyDataSetChanged();
}
public void remove(T elem) {
data.remove(elem);
notifyDataSetChanged();
}
public void remove(int index) {
data.remove(index);
notifyDataSetChanged();
}
public void replaceAll(List<T> elem) {
data.clear();
data.addAll(elem);
notifyDataSetChanged();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment