Pr.Pg Next Pg

Landscape Layout

 

Setting up the Landscape layout

  • So far we have worked mainly with portrait orientaion.

  • We can however set a customised horizontal layout for our activity.

  • In our MainActivity when we set the device in a horizontal manner, we willl se the following screen.

  • We can see a folder named layout-land in our package explorer.

  • Inside this folder we create new file named exactly the same as the file in the vertical layout, i.e in our case it is named as main.xml.

  • We can then change attributes of the various components and can also add components.

  • Note that the IDs of the various components in the vertical and horizontal layouts should be the same.

  • Below is a sample XML code for our main.xml in horizontal orientation.

 

 

Program for main.xml in horizontal orientation

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

 

<TextView

android:id="@+id/id_tv"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_gravity="center"

android:gravity="center"

android:textSize="40sp"

android:text="@string/hello" />

<LinearLayout

 

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="horizontal"

android:layout_gravity="center"

android:weightSum="100">

 

<Button

android:id="@+id/id_button1"

android:layout_width="250sp"

android:layout_height="wrap_content"

android:layout_gravity="center"

android:text="Click Me"

android:layout_weight="50" />

 

<Button

android:id="@+id/id_button2"

android:layout_width="250sp"

android:layout_height="wrap_content"

android:layout_gravity="center"

android:text="Change Activity"

android:layout_weight="50" />

 

 

</LinearLayout>

 

<TextView android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="This is text is visible only in Horizontal Orientation"

android:gravity="center"

android:textSize="25sp"/>

</LinearLayout>

 

  • Below is the screenshot how the activity will look in the horizontal orientation.

 

 

  • When this activity runs and when the orientation is changed the activity will restart and the data is reset, I,e, the onCreate() method for that activity will be called again.

  • To solve this issue inside the AndroidManifest.xml file, for that particular activity set an attribute like

  • android:configChanges="keyboardHidden|orientation"

 

And for API 13 or greater add this:

  • android:configChanges="keyboardHidden|orientation|screenSize"

  • This stop the activity to restart and the data wont be reset.

 

Pr.Pg border                                              Next Pg