public class CustomListAsyncTaskLoader extends AsyncTaskLoader<List> { private List list; private LoadListener listener; public CustomListAsyncTaskLoader(Context context, LoadListener listener) { super(context); this.listener = listener; }
@Override protected void onStartLoading() { // just make sure if we already have content to deliver if (list != null){ deliverResult(list); } // otherwise if something has been changed or first try if(takeContentChanged() || list == null){ forceLoad(); } }
// clear reference to object // it's necessary to allow GC to collect the object // to avoid memory leaking list = null; }
@Override public List loadInBackground() { // even if fail return empty list and print exception stack trace list = Collections.unmodifiableList((List) listener.loading()); return list; } public interface LoadListener { List loading(); } }
private LoaderManager.LoaderCallbacks<List> loaderCallbacks = new LoaderManager.LoaderCallbacks<List>() { @Override public Loader<List> onCreateLoader(int i, Bundle bundle) { progress_bar.setVisibility(View.VISITIY); return new CustomListAsyncTaskLoader(getActivity(), new LoadListener() { @Override public List loading() { return getDataList();//这里可以写自己的耗时的操作,如获取网络数据,获取数据库数据等 } }); }
@Override public void onLoadFinished(Loader<List> listLoader, List list) { progress_bar.setVisibility(View.GONE); mAdapter.setData(list); }
@Override public void onLoaderReset(Loader<List> listLoader) { mAdapter.clear(); } };
//这个是自定义Adapter中的setData方法 public void setData(List<T> dataList){ this.clear(); if(Build.VERSION.SDK_INT >= 11){ this.addAll(dataList); }else{ for(T data : dataList){ this.add(data); } } this.notifyDataSetChanged(); }