Skip to content

Instantly share code, notes, and snippets.

@DanielGrech
Last active August 29, 2015 14:04
Show Gist options
  • Save DanielGrech/b458fdb3559a182d2d1f to your computer and use it in GitHub Desktop.
Save DanielGrech/b458fdb3559a182d2d1f to your computer and use it in GitHub Desktop.
Base adapter subclasses which take some of the boilerplate out of displaying a list of items
import android.widget.BaseAdapter;
import java.util.List;
public abstract class BaseListAdapter<DataType> extends BaseAdapter {
private List<DataType> mItems;
@Override
public final int getCount() {
return mItems == null ? 0 : mItems.size();
}
@Override
public final DataType getItem(int position) {
return mItems.get(position);
}
public final void populate(List<DataType> items) {
mItems = items;
notifyDataSetChanged();
}
}
import android.view.View;
import android.view.ViewGroup;
public abstract class BaseViewConvertingAdapter<DataType, ViewType extends View> extends BaseListAdapter<DataType> {
protected abstract ViewType createView(ViewGroup parent);
protected abstract void populateView(DataType data, ViewType view);
@Override
public final View getView(int position, View convertView, ViewGroup parent) {
final ViewType view;
if (convertView == null) {
view = createView(parent);
} else {
view = (ViewType) convertView;
}
populateView(getItem(position), view);
return view;
}
}
public class PersonAdapter extends BaseViewConvertingAdapter<Person, TestListItem> {
public PersonAdapter() {
populate(Arrays.asList(
new Person("john smith", 40),
new Person("dave smith", 40),
new Person("daniel smith", 40),
new Person("greg smith", 40),
new Person("tom smith", 40)
));
}
@Override
protected PersonListItem createView(ViewGroup parent) {
return PersonListItem.inflate(parent, PersonListItem.class);
}
@Override
protected void populateView(Person data, PersonListItem view) {
view.populate(data);
}
@Override
public long getItemId(int position) {
return position;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment