简体   繁体   English

使用DrawerLayout保存片段的状态

[英]Saving state of fragment using DrawerLayout

I used this tutorial to make the SliderView. 我使用本教程制作了SliderView。

In the first fragment I have a media player with pause button, play button, and stop button. 在第一个片段中,我有一个带有暂停按钮,播放按钮和停止按钮的媒体播放器。 When I press the play button, it enables the others, and disable itself. 当我按下播放按钮时,它将启用其他按钮,并自行禁用。 After that, I go to the other fragment using the Slider Menu. 之后,我使用“滑块”菜单转到另一个片段。 And when I return to the first fragment where my media player is, the buttons are in the initial state. 当我回到媒体播放器所在的第一个片段时,按钮处于初始状态。 It calls the onCreateView again. 它再次调用onCreateView。

I need to know how to save the state of that fragment to show it later. 我需要知道如何保存该片段的状态以便以后显示。

Take a look at the Fragment docs over at Android's developer site. 在Android开发人员网站上查看Fragment文档。 In their example they show clearly how to save state here . 在他们的示例中,他们清楚地显示了如何在此处保存状态。 For ease of use I'll copy here :). 为了易于使用,我将在这里复制:)。

Basically, you have to check for saved state in onActivityCreated and save any desired info in onSaveInstanceState as follows: 基本上,您必须检查onActivityCreated中的已保存状态,并将任何所需的信息保存在onSaveInstanceState中,如下所示:

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

    .....

    if (savedInstanceState != null) {
        // Restore last state for your player information.
        mIsPlaying = savedInstanceState.getBoolean("isPlaying", false);
    }
    ......
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBoolean("isPlaying", mIsPlaying);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM