Android Landscape Layout example
In this post, we will be discussing about how to handle screen orientation changes in Android application. Users will often switch to landscape orientation for comfort or more horizontal screen space, but we must make sure that controls are accessible to User even if screen orientation is changed and also should feel comfortable to work on it.
We will take “Button listener” example(Button Listener – Make the cat start Meowing) to demonstrate how the controls change its position, size etc when the screen orientation is changed and also how to organize the controls when the orientation is changed to landscape layout.
Portrait and landscape view of “Button listener” application (Before adding landscape layout):
Landscape view of the application is really scary! I want to change it. 😉
How to add Landscape layout in Android application?
- Create ‘layout-land’ folder under /res folder where you need to put landscape layout xmls
- Create new Android layout XML under /res/layout-land folder with same name as there in /res/layout folder to make sure that the device will change between these two XMLs when screen orientation is changed.
- Its upto you how to organize the controls in the layout for the landscape orientation. Make sure that the resources that are referred in Activity class should be retained in the newly created XML file.
Landscape layout xml
I just need to use the same main.xml under /res/layout folder but have to do some changes.
Take a look at the landscape orientation xml:
<?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:gravity="center" android:orientation="horizontal" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="center" android:background="@drawable/kitty" /> </LinearLayout>
Changes that are made:
- android:orientation property in linear layout tag is set to horizontal to make sure that the layout will fit into the horizontal screen.
- android:layout_width property is set to wrap_content – Android device displays just the original size of the image
- android:layout_gravity property is set to center to display the image at the center of the device
We are done with developing landscape layout for “Button listener” example. We will test the application.
Run click on the project >> Run as >> Android application
Portrait and landscape view of the modified application:
Now the landscape view of the application looks good. 😀