Introduction to Layouts or ViewGroups
All the interaction of a user with the Android app is through the user interface, so it is very important to understand the basics about the User Interface of an android application, We have already learned about the various Views available in Android OS to create various User Interface (UI) components of your Android App.
But how can you arrange all view components for appearing in an ordered manner on the device’s screen and Android Layouts are used to arrange the views on the device’s screen.
ViewGroup is the base class for the layouts and view containers.
ViewGroup
A ViewGroup is a special view that can contain other views in android ui. The ViewGroup is the base class for Layouts in android, LinearLayout, RelativeLayout etc.
In other words, ViewGroup can be generally used to define the layout in which views(widgets) will be set/arranged/listed on the android screen.
ViewGroupsas an invisible container in which other Views and Layouts can be placed and yes, a layout can hold another layout in it, or in other words a ViewGroup can have another ViewGroup in it.
The class ViewGroup extends the class View.
We will learn about Layouts in depth in the upcoming lessons.
Most commonly used Android layout types
- LineraLayout
- RelativeLayout
- Web View
- TabularLayout
- ListView
- GridView
ListView and GridView act both as a View and a ViewGroup and you may ask how? Well, if we can use the ListView view to show some data in list form, it acts as a View. But if we use it for creating a list of some other view and for example an ImageView then it acts as a ViewGroup.
Also, the ViewGroup extends the class ViewGroup and which in turn extends the class View, so in a way all the ViewGroup subclasses are actually views, with some extra features.
Programmatic and Declarative Approach
To define/create a View or a ViewGroup in your android application, there are two possible ways:
The Programmatic Approach: In this we can define/create our Views in the Java source file. We will learn about this approach in detail later, as of now here is a sample code to add a Button to our view.
Button myButton = new Button(this); myButton.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); myLayout.addView(myButton);
So addView() is that the function that can be used to adding any View to the User Interface (UI) and setLayoutParams() function is used to set the various attributes.
The Declarative Approach:we can define the View as well as ViewGroups directly in the design XML files and like we will be doing in the next couple of tutorials where we will study about numerous commonly used views.
In the coming section we can learn about each of the famous layout types and how they can be used to arrange different view components and hence defining your Android app’s user interface.