Loader

在Activity或者Fragment中,使用LoaderManager管理一个或者多个Loader,一般常用的是CursorLoader。一般通过ContentProvider来取得。一般实现LoadManager.LoaderCallbacks接口来取得LoadManager进行initLoader()的回调。在onCreateLoader()中,实现通过ContentProvider来实例化Loader并返回。在onLoadFinished()中,进行adapter的的swap,更新数据。onLoadReset()在Loader重置并数据不可用时进行调用。

public static class CursorLoaderListFragment extends 
    ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
    SimpleCursorAdapter mAdapter;
    String mCurFilter;

    @Override public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ...
        // Prepare the loader.  Either re-connect with an existing one,
        // or start a new one.
        getLoaderManager().initLoader(0, null, this);
    }

    public boolean onQueryTextChange(String newText) {
        ...
        getLoaderManager().restartLoader(0, null, this);
        return true;
    }

    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new CursorLoader(getActivity(), baseUri,
                CONTACTS_SUMMARY_PROJECTION, select, null,
                Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    }

    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        mAdapter.swapCursor(data);
    }

    public void onLoaderReset(Loader<Cursor> loader) {
        mAdapter.swapCursor(null);
    }
}

results matching ""

    No results matching ""