如何从onCreate的Bundle中恢复Fragment实例?

时间:2014-08-01 16:31:53

标签: android android-activity android-fragments

我有一个Activity,其中包含一些在onCreate()中创建并由FragmentPagerAdapter(在getItem(int)中)返回的片段。这非常有效。如果活动被销毁然后重新创建(通过让手机进入睡眠状态很容易重现),旧的碎片将通过调用super.onCreate(Bundle)自动恢复,因为我已经将它传递给了' savedInstanceState& #39 ;.这就是我想要的。

问题是,我如何获得这些片段的引用?它们正在创建,但我无法访问它们。现在我每次调用onCreate()时都会重新创建片段,这是不理想的。

必须有办法做到这一点,对吧?

编辑:我根本没有使用FragmentManager。我正在使用FragmentPagerAdapter。一个例子如下。自定义片段是在onCreate()中创建的,是我想要指向重新创建的片段的内容。我需要引用这个片段,因为活动有时会调用它们的方法。

public class SectionsPagerAdapter extends FragmentPagerAdapter
{
    public SectionsPagerAdapter(FragmentManager fm)
    {
        super(fm);
    }

    @Override
    public Fragment getItem(int position)
    {
        Fragment fragment = null;

        switch (position)
        {
            case 0:
                fragment = myCustomFragment1;
                break;

            case 1:
                fragment = myCustomFragment2;
                break;

            case 2:
                fragment = myCustomFragment3;
                break;
        }

        return fragment;
    }

    @Override
    public int getCount()
    {
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position)
    {
        switch (position)
        {
            default:
            case 0:
                return "Fragment Title 1";

            case 1:
                return "Fragment Title 2";

            case 2:
                return "Fragment Title 3";
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以按ID或标记检索片段,具体取决于您创建它们的方式。

例如,在Activity

按ID:

// Fragment setup, with no tag
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_slot_in_the_layout, myFragment);
ft.commit();

...

// Now, we retrieve the fragment, somewhere else. 
// We can only do it by ID as no tag is available.
final FragmentManager fm = getSupportFragmentManager(); 
final Fragment fragment = fm.findFragmentById(R.id.fragment_slot_in_the_layout);

按标记:

// Fragment setup, using a tag
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_slot_in_the_layout, myFragment, TAG_THAT_YOU_HAVE_DEFINED);
ft.commit();

...

// Now, we retrieve the fragment, somewhere else. 
// You have the choice, you can retrieve it by ID or by tag as both are available. 
// In this example we retrieve it by tag.
final FragmentManager fm = getSupportFragmentManager(); 
final Fragment fragment = fm.findFragmentByTag(TAG_THAT_YOU_HAVE_DEFINED);

(如果您没有使用支持库,请使用Activity.getFragmentManager()代替Activity.getSupportFragmentManager()