1

您好 Android 开发人员,我遵循Android开发人员的显示图像指南,RetainFragment如果我旋转我的设备,我想从 a 加载我的初始化缓存。在我的ListFragments onActivityCreated()方法中执行此操作,但片段每次都是新创建的而不是重用。

我做这样的事情: RetainFragment

class RetainFragment extends Fragment {
private static final String TAG = "RetainFragment";
public LruCache mRetainedCache;

public RetainFragment() {}

public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
    RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);
    if (fragment == null) {
        fragment = new RetainFragment();
    }
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

}

和这个:ListFragment

@Override
public void onActivityCreated( Bundle savedInstanceState )
{
    super.onActivityCreated( savedInstanceState );

    RetainFragment mRetainFragment = RetainFragment.findOrCreateRetainFragment(getFragmentManager());
    LruCache mMemoryCache = RetainFragment.mRetainedCache;
    if (mMemoryCache == null) 
    {
        mMemoryCache = new LruCache(cacheSize);
        mRetainFragment.mRetainedCache = mMemoryCache;
    }
    else
    {
        mMemoryCache = mRetainFragment.mRetainedCache;
    }
    ...
}
4

1 回答 1

2

在我看来,他们忘记了以RetainFragment某种方式将其实际附加到Activity因此FragmentManager有机会找到它。未附加的片段不会在配置更改后继续存在。

不确定是否但它应该与下面的添加一起使用

public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
    RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);
    if (fragment == null) {
        fragment = new RetainFragment();
        // add this line
        fm.beginTransaction().add(fragment, TAG).commit();
    }
    return fragment;
}
于 2012-08-14T20:21:17.583 回答