user1177708
user1177708

Reputation: 15

Android - handling orientation changes when using fragments

I made two layout files - one for portrait and one for landscape. Here for portrait:

<?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>

Here for landscape:

   <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>

Then I created an Activity which loads the layout in the onCreate() method. So far, this works fine of course. This Activity doesn't contain more code than that.

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_news);
}

Inside the NewsListFragment class I am checking if the ViewNewsFragment is available. If not and the user tapped a ListItem a new Activity (that is ViewNewsActiviy) will be started. If it is available the data will show in the existing fragment. So there are two classes: 1. ViewNewsActivity and 2. ViewNewsFragment

But what I actually want is to change to layout on orientation changes. When the device is turned from portrait to landscape I want to have the typical Dual-Pane layout and if it's turned from landscape to portrait I want to show the list solely and the details should be viewed as separate "view".

But how to do this? Till now it works fine when you start the app either in landscape or in portrait. But when you change the orientation the layout remains as initially set.

I really appreciate any help :)! Thank you very much!

Jens

Upvotes: 0

Views: 2299

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006664

But how to do this? Till now it works fine when you start the app either in landscape or in portrait. But when you change the orientation the layout remains as initially set.

Android will automatically destroy and recreate your activity on an orientation change, and so each call to onCreate() will get the right layout.

If that is not happening for you, then you did something to stop it, such as by adding an android:configChanges attribute to the <activity> in the manifest.

Upvotes: 1

Related Questions