Skip to content

Instantly share code, notes, and snippets.

@delor
Last active August 29, 2015 14:15
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 delor/091921b1d5f892947390 to your computer and use it in GitHub Desktop.
Save delor/091921b1d5f892947390 to your computer and use it in GitHub Desktop.
An implementation of BaseAdapter which uses the new/bind pattern for its views.
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
/**
* An implementation of {@link BaseAdapter} which uses the new/bind pattern for its views.
*/
public abstract class BindableAdapter<T> extends BaseAdapter {
private final Context context;
private final LayoutInflater inflater;
public BindableAdapter(Context context) {
this.context = context;
inflater = LayoutInflater.from(context);
}
public Context getContext() {
return context;
}
@Override
public abstract T getItem(int position);
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = newView(inflater, position, parent);
if (view == null) {
throw new IllegalStateException("newView result must not be null.");
}
} else {
view = convertView;
}
bindView(getItem(position), position, view);
return view;
}
/**
* Create a new instance of a view for the specified position.
*/
public abstract View newView(LayoutInflater inflater, int position, ViewGroup container);
/**
* Bind the data for the specified {@code position} to the view.
*/
public abstract void bindView(T item, int position, View view);
@Override
public final View getDropDownView(int position, View view, ViewGroup container) {
if (view == null) {
view = newDropDownView(inflater, position, container);
if (view == null) {
throw new IllegalStateException("newDropDownView result must not be null.");
}
}
bindDropDownView(getItem(position), position, view);
return view;
}
/**
* Create a new instance of a drop-down view for the specified position.
*/
public View newDropDownView(LayoutInflater inflater, int position, ViewGroup container) {
return newView(inflater, position, container);
}
/**
* Bind the data for the specified {@code position} to the drop-down view.
*/
public void bindDropDownView(T item, int position, View view) {
bindView(item, position, view);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment