2

我有一个没有视图的片段,用于托管 AsyncTask。我想在配置更改(例如方向更改)期间保留片段对象。据我了解,在片段的 onCreate() 方法中使用 setRetainInstance(true) 就足够了。但这是我的问题:

首先让我发布一些我正在使用的代码。

我的活动在其 onCreate() 方法中使用它

protected void onCreate(Bundle savedState)
{
    super.onCreate(savedState);

    /* omitted - other initialization that takes place */

    fetcher = (DirectionsFetcherFragment)
        manager.findFragmentByTag(DIRECTIONS_FETCHER_FRAGMENT);
        if (fetcher == null)
        {
            Log.d(TAG, "Creating new DirectionsFetcherFragment instance");

            fetcher = DirectionsFetcherFragment.newInstance( /*omitted*/);

            transaction = manager.beginTransaction();
            transaction.add(fetcher, DIRECTIONS_FETCHER_FRAGMENT);
            transaction.commit();
        }
}

这是片段代码中的一些示例

class DirectionsFetcherFragment extends Fragment
{
    /* string constants omitted */


    public static DirectionsFetcherFragment newInstance(/*omitted*/)
    {
        DirectionsFetcherFragment instance = new DirectionsFetcherFragment();
        Bundle data = new Bundle();
        /* omitted - adding the necessary data to the bundle */
        instance.setArguments(data);
        return instance;
    }

    public DirectionsFetcherFragment()
    {
        super();
        /* omitted - setting default values for member variables */
    }

    @Override
    public void onCreate(Bundle savedInstance)
    {
        Log.wtf(TAG, "onCreate()");
        super.onCreate(savedInstance);
        setRetainInstance(true);
        Bundle arguments = getArguments();

        /* omitted - other initializations tasks that take place */
    }
}

这是正在发生的事情。在初始活动创建时,提取器引用为空,因此我创建了一个新片段并通过事务添加它。但是,当/如果我旋转设备时,当活动的 onCreate() 方法运行 fetcher 引用为 null 时,findFragmentByTag() 不会返回任何片段。在 LogCat 中,我可以清楚地看到片段的 onDetach() -> onAttach() 方法是针对第一个片段运行的,但由于某种原因,片段随后被垃圾收集并创建了一个新片段。

这是 LogCat 输出:

D/DirectionsViewer﹕ Initializing from intent <<-- Initial activity creation
D/DirectionsViewer﹕ Creating new DirectionsFetcherFragment instance <<-- Fragment creation
A/DirectionsFetcherFragment﹕ onAttach()
A/DirectionsFetcherFragment﹕ onCreate()
V/DirectionsViewer﹕ onStart()
V/DirectionsViewer﹕ onResume()
V/DirectionsViewer﹕ onSaveInstanceState() <<-- Rotationing and saving instance
A/DirectionsFetcherFragment﹕ onDetach() <<-- Fragment correctly detaches
D/DirectionsViewer﹕ Restoring from saved instance <<-- Activity restoration
D/DirectionsViewer﹕ Creating new DirectionsFetcherFragment instance <<-- Why is this happenning, shouldn't I get a reference to the existing fragment?
A/DirectionsFetcherFragment﹕ onAttach()
A/DirectionsFetcherFragment﹕ onCreate()
V/DirectionsViewer﹕ onStart()
V/DirectionsViewer﹕ onResume()
V/DirectionsViewer﹕ Deleting DirectionsViewer instance <<-- This is the old activity that gets garbage collected
A/DirectionsFetcherFragment﹕ Deleting DirectionsFetcherFragment instance <<-- This is the old fragment instance that gets garbage collected

我错过了什么吗?提前感谢您的任何答案。

4

0 回答 0