【发布时间】:2014-05-15 20:42:22
【问题描述】:
作为一个初学的 android 开发者,我遇到了关于屏幕方向改变时片段和活动处理的问题。
这是我的情况: 我有两个片段(F_A 和 F_B)。 F_A 包含 ListView (LV),F_B 包含几个 View 的组合:LV 的描述(我们称之为 Desc)。
当应用以纵向模式运行时,第一个 Activity 会显示 LV,然后在单击某个项目后会运行第二个 Activity。在这种情况下,当屏幕的方向从纵向模式更改为横向模式时,我想更改布局以显示两个片段,因为它是在应用程序最初以横向模式运行时完成的。
我希望提供的代码段不会混淆我对情况的描述:)
第一个活动 main_activity.java 文件包含:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // there is two actitivy_main.xml files
// one in layout/ directory and the other one in layout-land/ directory.
...
}
@Override
public void respond (int index) {
// this method got the second fragment if it is visible and not null.
// otherwise starts new activity for only description fragment (F_B)
}
第二个活动(仅适用于纵向模式) DescriptionActivity.java 文件包含:
@Override
protected void onSaveInstanceState(Bundle outState) {
// saving some stuff for further handling when orientation will changed from port to land.
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_description); // This layout contains only F_B fragment
... //here some initialization is done for the description.
}
考虑到在屏幕旋转期间会调用诸如 onPause()、onStart() 等生命周期保护方法,我认为我必须检查这些方法中的方向,然后销毁第二个活动并运行第一个:main_activity它本身会检查应该显示什么布局(在这种情况下是来自 layout-land/ 目录的布局,我不确定这是一个好主意,所以我想向有更多经验的开发人员寻求帮助。
非常感谢,
阿森
【问题讨论】:
-
如果你在 android 教程中搜索,你会发现一个教程解释了如何去做。 (如果我没记错的话)
-
您是否在该 Activity 的清单文件中设置了
configChanges="orientation"?如果是这样,您的onCreate函数将不会被调用,setContentView将无法从layout-land目录中提取正确的布局。 -
我在培训材料中搜索并没有找到有用的教程,但只是阅读了 Amilcar 的 1 个答案,它似乎可以帮助我找到解决方案。谢谢大家!
标签: android android-layout android-fragments android-activity landscape