Yon*_*Nir 5 android android-fragments android-activity
我有两个活动,A和B.每个活动都是一个容器,用于替换为a的片段FragmentTransaction.
我在某些设备上遇到问题,当用户在活动A中打开活动B时,第一个活动可能已被破坏,这意味着当用户单击后退按钮时,它会在正常设备中重新创建第一个活动,它会恢复.
我的主要问题是用户丢失了他在第一个活动中的片段堆栈.当用户打开第二个活动时,他已经将3个片段"深入"了第一个活动.如何恢复堆栈并将用户返回到第一个活动被销毁之前的位置?
这应该由 Android 操作系统自动处理。您可以打开开发人员选项“不保留活动”,以便当您的活动进入后台时始终模仿此行为(破坏您的活动)。之后就可以开始调试了。需要检查的一些事项:
在活动的onCreate中,您是否使用savedInstanceState调用超级onCreate?
如果在 onCreate 开始处放置断点,当您“返回”到 Activity 时,是否有保存的实例状态?
您在哪里创建片段?您是否手动重新创建它们(您不应该)?
您的片段是在布局中硬编码还是在布局中替换(替换容器视图)?
* 编辑 *
从您的回复中,我得出这就是问题所在,您说:“在 onCreate 的末尾,我用片段事务替换片段,从而加载应用程序的第一个片段”=> 当 savingInstanceState 时,您不应该这样做不为空。否则,您将破坏保存状态中已有的内容。
检查此处:https ://developer.android.com/training/basics/fragments/fragment-ui.html
注意当savedInstanceState不为null时的返回。
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
// Check that the activity is using the layout version with
// the fragment_container FrameLayout
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create a new Fragment to be placed in the activity layout
HeadlinesFragment firstFragment = new HeadlinesFragment();
// In case this activity was started with special instructions from an
// Intent, pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |