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

问题描述:

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

你应该保存在扩展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" ...... 机器人:名字= “对myApp。”'>

其他方法是通过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); 
+0

可以请你解释编码breifly? – Karthik

+0

我需要添加哪些代码? – user3811082