Sunday, March 3, 2013

How to use the LinearLayout in controlling the Android interface?

Just a brief description of the LinearLayout usage after going through couple of tutorial from few blog or website.

1. Create a project with the below configuration

Application Name: LinearLayout
Project Name: LinearLayout
Package Name: com.example.linearlayout

How to use layout_weight parameter?

2. Replace the layout as shown below to activity_main.xml with the layout xml as shown below
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 <Button
  android:id="@+id/button1"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_weight="1"
  android:text="Button 1" />
 <Button
  android:id="@+id/button2"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_weight="2"
  android:text="Button 2" />
 <Button
  android:id="@+id/button1"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_weight="1"
  android:text="Button 3" />
</LinearLayout>
Once the project is compiled and run, it will be displayed in the emulator as shown in the screen below. The size of each of the button will be controlled by the layout_weight ratio.
How to use gravity parameter?

3. Replace the layout as shown below to activity_main.xml with the layout xml as shown below
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
 <LinearLayout
     android:orientation="horizontal"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:layout_weight="1"
     android:gravity="left"
     android:background="#99F55500">
     <TextView
         android:id="@+id/textView1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="City"/>
 </LinearLayout>
 
 <LinearLayout
     android:orientation="horizontal"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:background="#99055500"
     android:layout_weight="1"
     android:gravity="right">
     <TextView
         android:id="@+id/textView2"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="New York"/>
 </LinearLayout>
</LinearLayout>

Once the project is compiled and run, it will be displayed in the emulator as shown in the screen below. You will notice that the textview is set to right alignment.




No comments: