7

给定一个片段,它使用加载器从数据库加载(大量)数据。

问题 :

我有一个寻呼机适配器,它在用户离开持有它的选项卡时破坏片段,并在用户返回该选项卡时重新创建它。由于这种重新创建,每次都会创建一个新的加载器,并且每次都会加载数据。

问题 :

为了避免每次创建fragment时都重新创建loader,是否可以getActivity.getSupportLoaderManager.initLoader(loaderId, null, false)在fragment的onActivityCreated方法中使用?

我已经尝试过,测试过它,它似乎工作正常。但我不相信这是正确的。

4

2 回答 2

2

实际上,检查源代码,你最终会做同样的事情。

Fragment.getLoaderManager:

/**
 * Return the LoaderManager for this fragment, creating it if needed.
 */
public LoaderManager getLoaderManager() {
    if (mLoaderManager != null) {
        return mLoaderManager;
    }
    if (mActivity == null) {
        throw new IllegalStateException("Fragment " + this + " not attached to Activity");
    }


    mCheckedForLoaderManager = true;
    mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, true);
    return mLoaderManager;
}

mWho基本上是片段ID。

final void setIndex(int index, Fragment parent) {
    mIndex = index;
    if (parent != null) {
        mWho = parent.mWho + ":" + mIndex;
    } else {
        mWho = "android:fragment:" + mIndex;
    }
}

不同之Activity.getLoaderManager()处在于谁将成为(root)

因此,即使您可以按照您的要求进行操作,直接从 Fragment 调用它也可能是一种更好的方法

免责声明:我只检查了最新版本的源代码,但我不希望它有很大的不同

于 2013-12-14T21:00:36.403 回答
0

May i ask why you are simply not retaining the Fragment? It seems that what you need is to create the Loader in the Fragment and create the fragment with setRetainInstance(true). In this case remember to provide a TAG when you add the fragment. This way the fragment will survive even to activity config changes and only the view will be recreated leaving your loader alive.

于 2013-12-20T16:19:00.400 回答