我有 3(A,B,C) fragment 和一个 Activity 。在 Activity 中添加了 fragment A,然后替换了 fragment B、C。现在 fragment A 替换为 fragment B。在 fragment B 中,我添加了一些细节。然后我锁定解锁屏幕后的屏幕..它是带有 fragment A(已添加)的打开 Activity 。如何在锁定和解锁屏幕后恢复 fragment B
最佳答案
您应该将状态保存在扩展 Application
的类中类,导致 Activity 将在显示更改(发生锁屏或方向更改)后释放。
您的新应用程序类:
public class myApp extends Application {
public int state; //field that keeps saved state
在你的 Activity 类中:
//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;
}
}
里面的 list
<application android:icon="@drawable/icon" android:label="@string/app_name"
...android:name=".myApp"`>
另一种方法是使用 Activity 先前通过 Bundle savedInstanceState
保存的状态.
在你的 Activity 类中:
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);
关于android - 锁定和解锁屏幕后恢复 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42623229/