有点晚了,但可能对正在阅读此问题的其他人有用。这是AsyncTaskLoader的一个实现:
public class EventListLoader extends AsyncTaskLoader<List<Event>> {
private List<Event> events;
public EventListLoader(Context context) {
super(context);
events = new ArrayList<Event>();
}
@Override
public List<Event> loadInBackground(){
//"Simply scrape some data and return it" as a list of events here.
}
@Override
public void deliverResult(List<Event> data) {
if (isReset()) {
releaseResources(events);
return;
}
List<Event> oldData = events;
events = data;
if (isStarted())
super.deliverResult(data);
releaseResources(oldData);
}
@Override
protected void onStartLoading() {
if (events != null && !events.isEmpty())
deliverResult(events);
if (takeContentChanged() || events == null || events.isEmpty())
forceLoad();
}
@Override
protected void onStopLoading() {
super.onStopLoading();
cancelLoad();
}
@Override
public void onCanceled(List<Event> data) {
super.onCanceled(data);
releaseResources(events);
}
@Override
protected void onReset() {
super.onReset();
onStopLoading();
releaseResources(events);
}
private void releaseResources(List<Event> data) {
if (data!= null && !data.isEmpty())
data.clear();
}
}
在 ListFragment 中使用它作为:
public class EventsListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<List<Event>> {
private static final int LOADER_ID = 0;
...
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
...
setListAdapter(new EventListAdapter());
if (savedInstanceState == null)
getLoaderManager().initLoader(LOADER_ID, null, this);
else
getLoaderManager().restartLoader(LOADER_ID, null, this);
}
@Override
public Loader<List<Event>> onCreateLoader(int id, Bundle args) {
return new EventLoader(getActivity());
}
@Override
public void onLoadFinished(Loader<List<Event>> loader, List<Event> data) {
((EventListAdapter) getListAdapter()).setData(data);
invalidateActionMode(); //Only if Contextual Action Bar (CAB) is used.
}
@Override
public void onLoaderReset(Loader<List<Event>> loader) {
((EventListAdapter) getListAdapter()).clearData();
}
如果我们将 EventListAdapter 定义为:
public class EventListAdapter extends BaseAdapter {
protected List<Event> mItems = new ArrayList<>();
@Override
public boolean isEnabled(int position) {
return true;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public Object getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
...
}
public void setData(List<Event> items){
mItems.clear();
mItems.addAll(items);
notifyDataSetChanged();
}
public void clearData(){
mItems.clear();
notifyDataSetChanged();
}
}