Understanding Linear Layout in Android

Understanding Linear Layout in Android

In this tutorial, we are going to look into Linear Layout in android in details. If you are looking for information about other layouts supported by android system, you can search our tutorials or you can simply follow this link.

Understanding layout in android is very important. Android layout is use to define UI in android application. In android, a single activity appears in the foreground of android window.

Each activity has a corresponding layout that it uses to build its user interface. This layout can also be created programmatically but it is not always the best practise since it will become hard to separate the UI code from the main logic codes.

The diagram below shows how android system works with layout. The xml layout file contains a ViewGroup that can house other Views or ViewGroups

layout

 So what is Linear Layout in android?

As the name implies, linear layout is one of android numerous layout ViewGroups that places its view components in a linear arrangement. It arranges its children either vertical or horizontally. This is because the linear layout has an orientation attribute that can be set to vertical or horizontal. The default setting of the layout is horizontal.

Android layout file is an xml file that is stored in the layout folder inside the resource folder. The ViewGroup is a subclass of the View class and it can contain one or many different View instance(s).

The xml layout file conventionally takes the name of the activity.java file that will use the layout to create its interface. For example, if we create an activity class called MainActivity.java that inherits from the main activity, the xml layout file for this activity will be named activity_main.xml.

Before we go into more detail about linear layout in android we will create a new android project that uses linear layout as its container.

 Create a new android project by following the steps listed below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidLayout

Package: com.inducesmile.androidlayout

Keep other default selections

Continue to click on next button until Finish button is active

Then click on Finish Button

Once you are done with your project, head over to the resource > layout folder and open the file called activity_main.xml. The code snippet is pasted below

<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"
    tools:context="com.inducesmile.androidlayout.MainActivity" >  
</LinearLayout>

In the above layout file, every layout file has a root ViewGroup. In our case the ViewGroup is a Linear Layout. The root also has xmlns:android attribute with a value of “http://schemas.android.com/apk/res/android”.xmlns:android initializes the namespace ‘android’.

The layout_width and layout_height is essential in every layout since it determines the width and height of the layout relative to android window.

As mentioned before, if the android:orientation attribute is not set, the android system will automatically use the default configuration value of this attribute.

 Linear Layout Orientation Attribute

Let’s add five button view controls in our linear layout file. This will help us to understand how linear layout orientation works. In the horizontal orientation, the ViewGroup children are arranged in a horizontal manner while in vertical orientation, the Views are arranged in a vertical or top-down manner.

You can drag and drop these Views in your layout if you are using the design view in your IDE or you can simply write the xml code for the button views in your code view. Now our layout file will look like this.

<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="horizontal"
    tools:context="com.inducesmile.androidlayout.MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_name" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_name" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_name" />

    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_name" />

</LinearLayout>

When android orientation is set to horizontal, the layout interface will look like the image below.

linear orientation

If we change the android orientation value to vertical, we will get an interface like the one below.

vertical orientation

The next question we will ask ourselves is how android system knows the layout file to use when an activity comes to the foreground. This will lead us to the next topic on how to set our linear layout file to our activity.

 Set layout file to an Activity

Remember that when we created our project; we created a default Activity file called ManiActivity.java and a corresponding layout file called activity_main.xml. The activity class uses this layout file to create its interface with an Activity class method called setContentView(int layoutresource). You can see this in our activity class as shown in the code below.

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {
   @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
    }
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
       getMenuInflater().inflate(R.menu.main, menu);
       return true;
   }

   @Override
    public boolean onOptionsItemSelected(MenuItem item) {
   // Handle action bar item clicks here. The action bar will
   // automatically handle clicks on the Home/Up button, so long
   // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

In the Activity class onCreate callback method, there is a line of code -setContentView(R.layout.activity_main);  the class uses it to create its content view. The parameter is generated by android system which refers to our activity_main.xml file. Note that we can actually create a new layout file in our layout folder and replace it with the one currently attached to our activity class.

You have seen how to use a linear layout in android. Now we will move further to learn how we can create a linear layout programmatically in android. As I stated before it is not always the best practice to do this programmatically but there are cases when it can come handy.

The activity class can only use a single View or ViewGroup to set its content view. If you use a single view what it implies is that you cannot add another view or ViewGroup to your activity class. That is while in most situations it is important that you use a ViewGroup because it will avail you the opportunity to add more View or ViewGroup to your layout.

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       LinearLayout linearLayout = new LinearLayout(this);
       linearLayout.setOrientation(LinearLayout.VERTICAL);
       LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(380, 100);
  
       Button buttonOne = new Button(this);
       Button buttonTwo = new Button(this);
       Button buttonThree = new Button(this);
       Button buttonFour = new Button(this);

       buttonOne.setText("Button One");
       buttonTwo.setText("Button Two");
       buttonThree.setText("Button Three");
       buttonFour.setText("Button Four");

       buttonOne.setLayoutParams(layoutParams);
       buttonTwo.setLayoutParams(layoutParams);
       buttonThree.setLayoutParams(layoutParams);
       buttonFour.setLayoutParams(layoutParams);

       linearLayout.addView(buttonOne);
       linearLayout.addView(buttonTwo);
       linearLayout.addView(buttonThree);
       linearLayout.addView(buttonFour);

       setContentView(linearLayout);
    }
    @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         // Inflate the menu; this adds items to the action bar if it is present.
         getMenuInflater().inflate(R.menu.main, menu);
         return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
          return true;
        }
        return super.onOptionsItemSelected(item);
   }
}

The code above adds four button Views in a linear layout and set it as the content view of the activity class. The linear layout is created programmatically as a ViewGroup and four other button Views are created and attached to the linear layout. When you run the code above in your device your application interface will look as shown below.

linearapp

This brings us to the end of this tutorial. You can also read our Relative layout, Frame layout and Grid layout tutorials to understand more about when to use each of the following layouts in your application.

Finally, if you have a question or suggestion kindly use our comment box. You can download the source code for this tutorial below.

No Responses

Add a Comment