Layout outlines the structure of the user interface in an Android app. It provides a broader arrangement based on which the UI components can be placed inside an application. There are two ways to define a layout.
XML – The developer can create the layout in the XML file which can be used by the Android app.
Runtime – The user can create views and view group objects programmatically and they get created at the run time.
In our blog today we will create a simple application with few UI elements and will draw them using linear layout. We will be using the XML definition to create the components. This application is not doing anything meaningful but is just a demonstration of the linear layout.
Linear Layout – As the name suggest in this layout the UI components are drawn vertically or horizontally in a single direction. You can define the direction using android:orientation attribute. In linear layout the view group children are defined one after the other. You can define gravity and margins inside a linear layout.
Let us write a simple example to see Linear layout in action.
Steps
1. Create an Android project. I have named it LayoutTest. You can name it whatever you want.
2. Once the project is complete you can see that the SDK has created necessary files and starting code for you.
3. Go to activity_main.xml inside the layout folder in the res folder of the project and change the default XML to the following
In the XML code above we are defining the vertical linear layout as you can see with the value of parameter android:orientation. In the code above we have created three UI components namely Textview, Button and EditText. These are standard Android UI components and we are just displaying them in a sequential manner.
4. Now let us look at the Mainactivity.java present in the src folder. This is the code created by the SDK and it calls the activity_main.xml as shown below.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Readers can try and use “horizontal” orientation and see how the UI gets displayed. They can also try and fix the issues that may come due to it.