[英]Android - handling orientation changes when using fragments
我制作了两个布局文件-一个用于纵向,一个用于横向。 这里是肖像:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<fragment
android:id="@+id/fragment_newslist"
android:name="com.app.NewsListFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" >
</fragment>
</LinearLayout>
这里是风景:
<fragment
android:id="@+id/fragment_newslist"
android:name="com.app.NewsListFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" >
</fragment>
<fragment
android:id="@+id/fragment_viewnews"
android:name="com.app.ViewNewsFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" >
</fragment>
然后,我创建了一个Activity,用于在onCreate()方法中加载布局。 到目前为止,这当然很好。 该活动所包含的代码不止于此。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
}
在NewsListFragment类中,我正在检查ViewNewsFragment是否可用。 如果不是,并且用户点击了ListItem,将启动一个新的Activity(即ViewNewsActiviy)。 如果可用,数据将显示在现有片段中。 因此有两个类:1. ViewNewsActivity和2. ViewNewsFragment
但是我真正想要的是在方向更改时更改布局。 当设备从纵向切换为横向时,我希望具有典型的双窗格布局,如果从横向切换为纵向,则我希望仅显示列表,并且详细信息应视为单独的“视图”。
但是该怎么做呢? 到现在,无论您横向还是纵向启动应用程序,它都可以正常工作。 但是,当您更改方向时,布局仍保持初始设置。
我非常感谢您的帮助:)! 非常感谢你!
詹斯
但是该怎么做呢? 到现在,无论您横向还是纵向启动应用程序,它都可以正常工作。 但是,当您更改方向时,布局仍保持初始设置。
Android将在方向改变时自动销毁并重新创建您的活动,因此每次调用onCreate()
都会获得正确的布局。
如果这对您而言没有发生,那么您可以做一些事情来阻止它,例如,在清单中的<activity>
中添加android:configChanges
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.