Last active
November 12, 2015 19:30
-
-
Save mandybess/58686a46aa8ef1327fca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.Fragment; | |
import android.content.Context; | |
import android.os.Bundle; | |
import android.support.annotation.Nullable; | |
import android.view.LayoutInflater; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.widget.AdapterView.OnItemClickListener; | |
import android.widget.ArrayAdapter; | |
import android.widget.ListView; | |
import java.util.List; | |
import rx.Observable; | |
public abstract class BaseListFragment<T> extends Fragment implements OnItemClickListener { | |
protected ListAdapter mAdapter; | |
@Override public void onResume() { | |
super.onResume(); | |
loadData(); | |
} | |
@Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, | |
Bundle savedInstanceState) { | |
View view = inflater.inflate(getFragmentLayoutId(), container, false); | |
ListView list = (ListView) view.findViewById(getListViewId()); | |
mAdapter = new ListAdapter(getActivity(), getListItemLayoutId()); | |
list.setAdapter(mAdapter); | |
list.setOnItemClickListener(this); | |
return view; | |
} | |
protected abstract Observable<List<T>> fetchDataObservable(); | |
protected void loadData() { | |
fetchDataObservable() | |
.finallyDo(this::finallyDo) | |
.subscribe(list -> { | |
mAdapter.clear(); | |
mAdapter.addAll(list); | |
mAdapter.notifyDataSetChanged(); | |
}, this::doOnError); | |
} | |
protected abstract void finallyDo(); | |
protected abstract void doOnError(Throwable e); | |
protected abstract int getFragmentLayoutId(); | |
protected abstract int getListViewId(); | |
protected abstract int getListItemLayoutId(); | |
protected abstract void bindListItemView(View view, T item); | |
public class ListAdapter extends ArrayAdapter<T> { | |
private final int layoutRes; | |
public ListAdapter(Context context, int resource) { | |
super(context, resource); | |
layoutRes = resource; | |
} | |
@Override public View getView(int position, View convertView, ViewGroup parent) { | |
if (convertView == null) { | |
convertView = View.inflate(getContext(), layoutRes, null); | |
} | |
final T item = getItem(position); | |
bindListItemView(convertView, item); | |
return convertView; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment