2017-03-06 106 views
0

我有3(A,B,C)片段和一個activity.fragment A在活動中添加,然後片段B,C replacement.now片段A替換片段B在片段B我添加一些細節。然後我解鎖屏幕後鎖定屏幕..它是打開的活動與片段A(增加)。如何恢復片段B後鎖定和解鎖屏幕鎖定和解鎖屏幕後恢復片段

回答

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" ...... 機器人:名字= 「對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