锁定和解锁屏幕后恢复片段

时间:2017-03-06 10:30:20

标签: android android-service

我有3个(A,B,C)片段和一个activity.fragment A在活动中添加然后片段B,C被替换。现在片段A被替换为片段B.in片段B我添加了一些细节。然后我锁定解锁屏幕后的屏幕..是打开活动的片段A(已添加)。如何在锁定和解锁屏幕后恢复片段B

1 个答案:

答案 0 :(得分:1)

您应该在扩展Application类的类中保存状态,因为显示更改后会释放活动(发生锁定屏幕或方向已更改)。

您的新申请类:

public class myApp extends Application {
   public int state; //field that keeps saved state

在您的活动类中:

//add this method to save changed state
//then call it every time you change the fragment index
private void onChangeFragment(int stateid) {
    myApp sapp = (myApp) this.getApplication(); 
    sapp.state = stateid;
}

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

    myApp sapp = (myApp) this.getApplication();              
    //restore fragment from sapp.state value
    switch (sapp.state) {
        case 0 : //fragment A
            {  setContentView(R.layout.fragmentA);
               //maybe Fragment newFragment = new MyFragmentA(); ... and so on
               break;  
            }
        case 1 : //fragment B
            {  setContentView(R.layout.fragmentB);
               //maybe Fragment newFragment = new MyFragmentB(); ... and so on
               break;  
            }
    }

内部清单      <application android:icon="@drawable/icon" android:label="@string/app_name" ... android:name =“。myApp”`&gt;

其他方式是通过Bundle savedInstanceState使用活动以前保存的状态。

在您的活动类中:

private int state; //field that keeps saved state

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    state = savedInstanceState.getInteger(FRAGMENT_STATE_KEY);
    //restore the fragment from state value here
    //switch (state) {....
    //....
}

// invoked when the activity may be temporarily destroyed, save the instance state here
@Override
public void onSaveInstanceState(Bundle outState) {
    out.putInteger(FRAGMENT_STATE_KEY, state);

    // call superclass to save any view hierarchy
    super.onSaveInstanceState(out);