Layout :
A layout defines the Design or structure for a user interface in your app, such as in an activity. All elements in the layout are built using a hierarchy of View
and ViewGroup
objects. user can see views and interact with it. but ViewGroup
is invisible and that defines the layout structure for View
and other ViewGroup
objects
The View
objects are usually called “widgets” and can be one of many subclasses, such as Button
or
TextView
. The ViewGroup
objects are usually called “layouts” can be one of many types that provide a different layout structure, such as LinearLayout, Relativelayout etc
Write the XML :
In Android’s XML file , you can quickly design UI layouts and the screen elements they contain, in the same way you create web pages in HTML — with a series of nested elements. Each layout file must contain exactly one root element, that must be a View
or ViewGroup
object. Once you have defined the root element, you can add additional layout objects or widgets as child elements to build a View
hierarchy that defines your layout.
For example, here’s an XML layout that uses a vertical LinearLayout to hold TextView
and a Button
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
After declaring your layout in XML, save the file with the .xml extension, in your Android project’s res/layout directory, so it will properly compile when we run the app.
Load the XML Resource :
When we compile an app, each XML layout file is compiled into a View resource. We have to load this layout resource into the app code, for that we have to call a callback method onCreate(
) inside the Activity class. Inside onCreate()
it executes setContentView()
method we are passing layout file it executes and compiles and loads into the app code.
onCreate()
callback method inside the Activity class . we are setting this layout resource file to setContentView()
, we are passing layout resource file in the form of R.layout_file_name
.
For example, if your XML layout is saved as main_layout.xml
, you would load it for your Activity as shown below:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
The onCreate()
callback method in your Activity is called by the Android framework when your Activity is launched. Inside onCreate()
method setContentView()
method is executed and it call’s layout resource and executes and out put’s the view to the as UI for user.
Resource Attributes :
Every View
and ViewGroup
object supports their own XML attributes. Some attributes are specific to a View
object, but these attributes are also inherited by any View
objects that may extend this class
ID :
All the View
object’s may have an integer ID associated with it, to identify the unique View
within the tree. When the app is compiled, this ID is used as an integer, but the ID is typically assigned in the layout XML file as a string, in the id attribute.
android:id="@+id/my_button"
The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must be created and added to our resources (in the R.java file).
android:id="@android:id/empty"
With the android package, we are referencing an ID from the android.R resources class, not the local created resources class.
In order to create views and reference them from the app, a common pattern is to:
- Define a view/widget in the layout file and assign it to a unique ID:
<Button android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/my_button_text"/>
- Inside the main Activity’s
onCreate()
method we are creating instance ofView
object to access from the layout file.
Button button = (Button)findViewById(R.id.my_button);
wrap_content
expands size according to the content.match_parent
tells your view to become as big as its parent view group will allow.
Common Layouts :
Each subclass of the ViewGroup
class provides a unique way to display the views you nest within it
*****************************
Note: Although you can nest one or more layouts within another layout to achieve your UI design, you should strive to keep your layout hierarchy as shallow as possible. Your layout draws faster if it has fewer nested layouts (a wide view hierarchy is better than a deep view hierarchy).
*******************************
Linear Layout :
A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen.
Below is sample example code for LinearLayout :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="horizontal"
android:gravity="center">
--------------
------------
</LinearLayout>
Relative Layout :
It is a view group that displays child views in relative positions. The position of each view can be specified as relative to the elements, in positions relative to the parent RelativeLaout such as aligned to the bottom, left or center. ReativeLayout eliminate the nested view groups and keep your layout hierarchy flat, and improves the performance. In RelativeLayout child views are specify their position relative to the parent view or to each other (specified by ID). So you can align two elements by right border, or make one below another, centered in the screen, centered left, and so on.
Building Layouts with an Adapter :
When we are fetching the data or content for your layout from the data base or from the server means the dynamic data or content that is not pre-determined, At that time we can use a layout that subclasses AdapterView
to populate the layout with views at runtime. AdapterView
class has a sub class named as Adapter
. Adapter
class interacts with database OR server and fetches data and converts into view and asign’s to AdapterView
Class to display at runtime as UI. Here Adapter
class acts as a mediater between database or server and the AdapterView
class
Common layouts backed by an adapter include:
List View :
ListView is a view group that displays all the items in a list of scrollable items means list is more than device length. The list items are automatically inserted to the list using an Adapter it acts as a mediator between AdpterView and Database that pulls content from a source such as an array or database query and converts each item result into a view that’s placed into the list using AdapterView. Displays a scrolling single column list. For better performance use RecycleView to build List.
Grid View :
Displays a scrolling grid of columns and rows. The grid items are automatically inserted to the layout using a ListAdapter.
Below sample code describes about GridView layout in details how to use in xml layout fie
<?
xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
Filling an adapter view with data :
You can display or populate an AdapterView
such as ListView
or GridView
by binding the AdapterView
instance to an Adapter
, which retrieves data from an external source and creates a View that represents each data entry.
Android provides several subclasses of Adapter
that are useful for retrieving different kinds of data and building views for an AdapterView
.
The two most common adapters are:
ArrayAdapter
:
Use this ArrayAdapter
when your data source is in the form of an array. By default, ArrayAdapter
creates a view for each array item by calling toString()
on each item and placing the contents in a TextView
.
For example, if you have an array of strings you want to display in a ListView
, initialize a new ArrayAdapter
using a constructor to specify the layout for each string and the string array:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myStringArray);
The arguments for this constructor are:
- Your app
Context
- The layout that contains a
TextView
for each string in the array - The string array
Then call setAdapter()
on your ListView
:
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
If you want to customize the appearance of each item then override the toString()
method for the objects in your array. Or, to create a view for each item that’s something other than a TextView
(for example, if you want an ImageView
for each array item), extend the ArrayAdapter
class and override getView()
method to return the type of view you want for each item.
SimpleCursorAdapter:
When data comes from Cursor use Adapter. We will specify a layout for each row in the Cursor and which column in the Cursor inserted into which view of the layout by using SimpleCursorAdapter
.
For example, if you want to create a list of people’s names and phone numbers and email, you can perform a query that returns a Cursor containing a row for each person and columns for the names, numbers and email.
We can create a string array specifying the columns from the Cursor we want in the layout for each result and an integer array specifying the respective views that each column should be placed.
String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
int[] toViews = {R.id.display_name, R.id.phone_number};
When you initiate the SimpleCursorAdapter
, it pass the layout to use for each result, the Cursor
containing the results, and the two arrays:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.person_name_and_number, cursor, fromColumns, toViews, 0);
ListView listView = getListView();
listView.setAdapter(adapter);
The SimpleCursorAdapter
creates a view for each row in the Cursor
using the provided layout by inserting each fromColumns item into the respective view.
Handling click events
For example: Below sample code demonstrates for Click events to handle in java code, In this example code we are using OnItenclickListener and AdapterView .
// Create a message handling object as an anonymous class.
private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
// Do something in response to the click
}
};
listView.setOnItemClickListener(mMessageClickedHandler);
Congratultions You haveLearned About Android Layouts With Sample Examples