片段变为空

时间:2015-06-22 15:59:23

标签: java android android-fragments android-activity

我正在开发Android应用程序,我在我的主要活动中有一个片段:

        searchInnerPlaylistFragment = InnerPlaylistFragment.newInstance();

        Bundle bdl = new Bundle();
        bdl.putString(InnerPlaylistFragment.PLAYLIST_ID_KEY, ytf.getId());
        bdl.putString(InnerPlaylistFragment.PLAYLIST_TITLE_KEY, ytf.getTitle());
        bdl.putInt(InnerPlaylistFragment.PLAYLIST_VIDEO_NUMBER_KEY, videoNum);
        searchInnerPlaylistFragment.setArguments(bdl);

        ft.replace(R.id.search_inner_list_fragment, searchInnerPlaylistFragment).commit();

当我打开"不要保持活动"开发人员选项中的选项,并使用我的应用转到后台并返回到应用searchInnerPlaylistFragment变为空,但它仍然在活动中。

可以选择保存此片段吗?

2 个答案:

答案 0 :(得分:1)

要正确保存Fragment的实例状态,您应该执行以下代码:

在片段中,通过覆盖onSaveInstanceState保存实例状态并在onActivityCreated上恢复:

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ...
    if (savedInstanceState != null) {
        //Restore the fragment's state here
    }
}
...
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

//Save the fragment's state here


}

重要的是,在活动中,你必须在onSaveInstanceState上保存片段的实例并在onCreate上恢复。

public void onCreate(Bundle savedInstanceState) {
    ...
    if (savedInstanceState != null) {
        //Restore the fragment's instance
        mContent = getSupportFragmentManager().getFragment(
                    savedInstanceState, "mContent");
        ...
    }
    ...
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

//Save the fragment's instance
getSupportFragmentManager().putFragment(outState, "mContent", mContent);


}

希望得到这个帮助。

答案 1 :(得分:0)

你可以将你的片段放在backStack上,这样当你按下或导航到后面的屏幕时你可以从堆栈中取回它

将您的片段替换为

ft.replace(R.id.search_inner_list_fragment,searchInnerPlaylistFragment).addToBackStack()。commit();

当你想要获得这个片段时,你可以弹出它     manager.popBackStack();