Pages

Thursday, May 19, 2011

Android Layout Tutorial-Alternate Layouts

Alternate Layouts

On the LinearLayout page I mentioned that Android will shrink elements when they don’t all fit on the screen. You can reduce the need for this by using alternate layouts for different screen orientations. So, for example, you have a LinearLayout that looks pretty good in Landscape but does not have the room it needs in Portrait mode. Before looking in the res/layout folder for your layout XML Android will check for one of these alternate layouts.
  • res/layout-land – The alternate layout for a landscape UI
  • res/layout-port – The alternate layout for a portrait UI
  • res/lauout-square – The alternate layout for a square UI
There are many Alternate Resource types you can use in addition to screen orientation. A more complete list can be found here.
I am going to create a folder named layout-land under the res folder and place this XML under the new folder. The XML file should have the same name it has in the layout folder, in my case linear_layout.xml.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="horizontal"
 android:layout_width="fill_parent"
    android:layout_height="fill_parent">
     <Button 
     android:id="@+id/backbutton"
     android:text="Back"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    <TextView
     android:text="First Name"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    <EditText
     android:width="100px"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    <TextView
     android:text="Last Name"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    <EditText
     android:width="100px"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" /> 
</LinearLayout>
In the Emulator you can press 7 on your numberpad to change between Landscape and Portrait orientations. When I switch to landscape I see the Layout from the layout-land folder.
LinearLandscape
That wraps up my article on the standard layouts that come with Android. As always, please leave comments with any questions you have on the subject, or anything you would like to see elaborated on in a future article. Thank you for reading.

No comments:

Post a Comment

Popular Posts