Prashant Thakkar

Prashant Thakkar's page

Team member – Xoriant Mobile Center of Excellence.
31
Dec

At times we are in need to store some data locally for faster retrieving and processing. One of the ways to store data locally is to write it in the file, and read it whenever needed. But there is another approach of using Database. Advantages of using database are like one doesn’t need to read entire file, load it in memory for getting some small chuck of data, also from developer perspective retrieve data from database would be easier.

In this article we will look at how to use android’s inbuilt supported sqlite database.

Let us look at the example of employee_database with employee table having columns _id, emp_name, emp_designation. With _id set as integer, primary key and autoincrement and emp_name and emp_designation to string/text.


package com.dbexample;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class EmployeeTable{

	public static final String KEY_NAME = "emp_name";
	public static final String KEY_DESIGNATION = "emp_designation";
	public static final String KEY_ROWID = "_id";

	private static final String TAG = "EmployeeTable";
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;

	private static final String DATABASE_NAME = "employee_database";
	private static final String DATABASE_TABLE = "employee";
	private static final int DATABASE_VERSION = 3;

	/**
	 * Database creation sql statement
	 */
	private static final String DATABASE_CREATE =
		"create table " + DATABASE_TABLE + " (" + KEY_ROWID + " integer primary key autoincrement, "
		+ KEY_NAME +" text not null, " + KEY_DESIGNATION + " text not null);";

	private final Context mCtx;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			Log.i(TAG, "Creating DataBase: " + DATABASE_CREATE);
			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			onCreate(db);
		}
	}

	/**
	 * Constructor - takes the context to allow the database to be
	 * opened/created
	 *
	 * @param ctx the Context within which to work
	 */
	public EmployeeTable(Context ctx) {
		this.mCtx = ctx;
	}

	public EmployeeTable open() throws SQLException {
		Log.i(TAG, "OPening DataBase Connection....");
		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	public long createEmployee(String empName, String empDesignation) {
		Log.i(TAG, "Inserting record...");
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_NAME, empName);
		initialValues.put(KEY_DESIGNATION, empDesignation);

		return mDb.insert(DATABASE_TABLE, null, initialValues);
	}

	public boolean deleteEmployee(long rowId) {

		return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	public Cursor fetchAllEmployee() {

		return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
				KEY_DESIGNATION}, null, null, null, null, null);
	}

	public Cursor fetchEmployee(long empId) throws SQLException {

		Cursor mCursor =

			mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
					KEY_NAME, KEY_DESIGNATION}, KEY_ROWID + "=" + empId, null,
					null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;

	}

	public boolean updateEmployee(int empId, String empName, String empDesignation) {
		ContentValues args = new ContentValues();
		args.put(KEY_NAME, empName);
		args.put(KEY_DESIGNATION, empDesignation);

		return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + empId, null) > 0;
	}

}

In above example, EmployeeTable class has a private inner class DatabaseHelper which extends SQLiteOpenHelper class. SQLiteOpenHelper calss is responsible for calling onCreate and onUpgrade method whenever database is opened for either read or writes operation. onCreate method will check whether the table exist if not will create it, similarly onUpgrade method. Beside inner class EmployeeTable contains various other methods to createEmployee, deleteEmployee etc.

Snippet for Inserting Employee


EmployeeTable employeeTable = new EmployeeTable(this);
    	employeeTable.open();
    	employeeTable.createEmployee("Prashant Thakkar", "Tech Lead");
    	employeeTable.close();

Create instance of EmployeeTable and call it’s open() method. open method of EmployeeTable will create instance of DatabaseHelper and will open database connection with write permission. After open method is called, now call createEmployee method which accepts 2 parameter employee name and designation, this will insert a record in table employee. Since emp_id is set to autoincrement while creating database it will be set appropriately. Similarly close() method of EmployeeTable will close the database connection.
Snippet for retrieving Employee

EmployeeTable employeeTable = new EmployeeTable(this);
    	employeeTable.open();
    	Cursor c = employeeTable.fetchEmployee(1);
    	Toast.makeText(this, “Name: ” + c.getString(1) + “ Designation: “+ c.getString(2), Toast.LENGTH_LONG).show();
    	employeeTable.close();

fetchEmployee method of EmployeeTable accepts empId as parameter and returns cursor pointing to employee.
CursorAdapter
Let us look at how we can directly use cursor returned, for populating ListView.

EmployeeTable employeeTable = new EmployeeTable(this);
employeeTable.open();
Cursor c = employeeTable.fetchAllEmployee();
if (c != null){
SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(this,
		R.layout.listview,
		c, // Give the cursor to the list adapter
	new String[] {c.getColumnName(1),c.getColumnName(2)}, // Map the column in the
		// employee database to...
new int[] {R.id.EmployeeName, R.id.EmployeeDesignation}); // The view defined in the XML template
		ListView empListView = (ListView)findViewById(R.id.Employee);
		empListView.setAdapter(adapter2);
		}
		employeeTable.close();

listview.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/MainLayout">
	<TextView android:id="@+id/EmployeeName" android:layout_alignLeft="@id/MainLayout"
		android:layout_width="wrap_content" android:layout_height="wrap_content" />
	<TextView android:id="@+id/EmployeeDesignation" android:layout_alignParentRight="true" android:layout_toRightOf="@id/EmployeeName"
		android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RelativeLayout>

Point to remember is for using cursor for this kind of data binding operations we need to make sure that respective table have one column as _id
Conclusion
In this article introduces basics of Android SQLite database, created database and table, fetched records from database and also learned how to use SimpleCursorAdapter .

Prashant Thakkar
Prashant Thakkar– Team member – Xoriant Mobile Center of Excellence.

05
Aug

An application menu is critical to any mobile application. This is because real estate in a mobile device is limited, so the developer has to make judicious use of menus to provide good application usability. Android provides us with various ways to introduce a menu. This blog post will cover the different types of menus that you can include in your Android application along with code samples and screenshots.

Android Menus can be classified into 3 types:

  • Options Menu
  • Context Menu
  • Submenu

Options Menu:

Options Menu is the menu displayed when MENU key on the device is clicked.

Options menu is divided into 2 types: Icon Menu and Expanded Menu, based on the number of menu options. Options menu can have any number of menu options, but only the first six options are shown directly when the MENU key is clicked and this is called as Icon Menu. In case there are more than six options then first five are show directly and remaining are available when More button is clicked and is called as Expanded Menu.

Note: It is not mandatory to have icon for Icon Menu options. In case icons are associated with menu options,then the icons are displayed for Icon Menu only.

Important Points:

  • onCreateOptionsMenu() method of the Activity is called when the user clicks the Menu Key of the device. So override this method in the activity and populate the Menu object passed as parameter to this method.
  • Multiple add() methods are available. Use the one that accepts itemId as a parameter.
  • onOptionItemSelected() method of the activity is called when a particular Item/Option of the menu is clicked. Override this method in the activity and implement your code to perform the corresponding actions based on the menu option selected.
  • setIcon() is used for assigning icon with the option.

The listing below shows how to add a menu dynamically via code. We are overriding the onCreateOptionsMenu method that is automatically invoked when the User clicks on the MENU key on the device.

public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_ADD, 0, "Add").setIcon(R.drawable.ic_menu_add);
menu.add(0, MENU_DELETE, 0, "Delete").setIcon(R.drawable.ic_menu_delete);
menu.add(0, MENU_SAVE, 0, "Save").setIcon(R.drawable.ic_menu_save);
menu.add(0, MENU_DONE, 0, "Done").setIcon(R.drawable.ic_menu_done);
menu.add(0, MENU_HELP, 0, "Help").setIcon(R.drawable.ic_menu_help);
menu.add(0, MENU_SETTINGS, 0, Settings").setIcon(R.drawable.ic_menu_settings);
menu.add(0, MENU_EXIT, 0, "Exit").setIcon(R.drawable.ic_menu_exit);
return true;
}

The listing below shows how to you can react to different menu items that are clicked. We are only displaying the template below. The actual implementation when a specific menu item is clicked depends on your application.

public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case MENU_ADD:
// Add
<span style="white-space: pre;"> </span>return true;
case MENU_DELETE:
// Delete
<span style="white-space: pre;"> </span>return true;
case MENU_SAVE:
// Save
<span style="white-space: pre;"> </span>return true;
case MENU_DONE:
// Done
<span style="white-space: pre;"> </span>return true;
case MENU_HELP:
// Help
return true;
case MENU_SETTINGS:
// Settings
<span style="white-space: pre;"> </span>return true;
case MENU_EXIT:
// Exit
<span style="white-space: pre;"> </span>return true;
default:
<span style="white-space: pre;"> </span>return false;
}   <span style="white-space: pre;"> </span>
}

Context Menu:

Android provides the facility to open a menu in context with the object clicked. A Long-press on the view will bring up the registered Context menu.

Important Points

  • Using registerForContextMenu() method view is registered for context menu.
  • onCreateContextMenu() method of Activity is called on click (long-press) of registered view. So override this method to populate Context menu options.
  • onContextItemSelected() method of activity is called whenever item/option from context menu is selected. Override this method to perform the appropriate operations depending on the option selected.
public void onCreateContextMenu(ContextMenu menu, View v,

 ContextMenuInfo menuInfo) {

 super.onCreateContextMenu(menu, v, menuInfo);

 menu.add(0, MENU_ADD, 0, "Edit");

 menu.add(0, MENU_DELETE, 0, "Delete");

}

public boolean onContextItemSelected(MenuItem item) {

 switch(item.getItemId()){

 case MENU_ADD:

 // Add

 return true;

 case MENU_DELETE:

 // Delete

 return true;

 default:

 return false;

 }

}

For this example context menu is register to be shown on TextView. Here tv is an instance of a TextView that is present on the layout of this activity.
registerForContextMenu(tv);
Context Menu

Menu Using XML

Menu can also be defined and populated using XML. Following XML structure represents the same menu as of above.
Create optionsmenu.xml under folder res/menu
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:id="@+id/MENU_ADD"  android:title="Add"
 android:icon="@drawable/ic_menu_add"/>
 <item android:title="Delete" android:id="@+id/MENU_DELETE" android:icon="@drawable/ic_menu_delete"/>
 <item android:title="Save" android:id="@+id/MENU_SAVE" android:icon="@drawable/ic_menu_save"/>
 <item android:title="Done" android:id="@+id/MENU_DONE" android:icon="@drawable/ic_menu_done"/>
 <item android:title="Help" android:id="@+id/MENU_HELP" android:icon="@drawable/ic_menu_help"/>
 <item android:title="Settings" android:id="@+id/MENU_SETTINGS" android:icon="@drawable/ic_menu_settings"/>
 <item android:title="Exit" android:id="@+id/MENU_EXIT" android:icon="@drawable/ic_menu_exit"/>
</menu>

public boolean onCreateOptionsMenu(Menu menu) {
 MenuInflater inflater = new MenuInflater(this);
 inflater.inflate(R.menu.optionsmenu, menu);
 return true;
}

Advantages of using XML for creating menu are:

  • Easily maintain/modify the menu structure due to a clear separation of the menu creation from the code.
  • The code in onCreateOptionsMenu() method is reduced.

Submenus

Sub menu can be added to any type of menu.

Below code shows adding Submenu  for Options menu:

public boolean onCreateOptionsMenu(Menu menu) {

  SubMenu sendMenu = menu.addSubMenu("Send");

sendMenu.add(0,MENU_SMS,0,"SMS");

  sendMenu.add(0,MENU_EMAIL,0,"EMAIL");

 return true;

}

public boolean onOptionsItemSelected(MenuItem item) {

switch(item.getItemId()){

 case MENU_SMS:

 // SMS

 return true;

 case MENU_EMAIL:

 // Email

 return true;

 default:

 return false;

 }

}
Submenu

Submenu

<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/MENU_SEND"
 android:title="Send">
 <menu>
 <item android:id="@+id/MENU_SMS" android:title="SMS"></item>
 <item android:id="@+id/MENU_EMAIL" android:title="EMAIL"></item>
 </menu>
</item>
</menu>
As covered in this blog post, Android provides several ways to include menus in your application. You should pick and choose them depending on your needs. Context Menus are typically expected now by users and should be used carefully in order to provide good application usability.

Prashant Thakkar
Prashant Thakkar– Team member – Xoriant Mobile Center of Excellence.

15
Jul

This blog post introduces one of the important mechanism of Async Task for Android with sample code.

Android implements single thread model and whenever an Android application is launched, a thread is created. Now assume you have long running operations like a network call on a button click in your application. On button click a request would be made to the server and response will be awaited. Now due to the single thread model of Android, till the time response is awaited your UI screen hangs or in other words, it is non-responsive.

We can overcome this by creating a new Thread and implement the run method to perform the time consuming operation, so that the UI remains responsive.

As shown below a new Thread is created in onClick method

public void onClick(View v) {
    Thread t = new Thread(){
    public void run(){
	// Long running operation
	  }
   };
   t.start();
}

But since Android follows single thread model and Android UI toolkit is not thread safe, so if there is a need to make some change to the UI based on the result of the operation performed, then this approach may lead some issues.

There are various approaches via which control can be given back to UI thread (Main thread running the application). Handler approach is one among the various approaches.

Handler

Let us look at the code snippet below to understand Handler approach.

public void onClick(View v) {
   Thread t = new Thread(){
	public void run(){
   	   // Long time comsuming operation
	 	Message myMessage=new Message();
		Bundle resBundle = new Bundle();
		resBundle.putString("status", "SUCCESS");
		myMessage.obj=resBundle;
		handler.sendMessage(myMessage);
	}
  };
  t.start();
}

As seen we have modified the original run method and added code to create Message object, which is then passed as parameter to sendMessage method of Handler. Now let us look at the Handler. Note that the code below is present in the main activity code.

private Handler handler = new Handler() {
@Override
	public void handleMessage(Message msg) {
		// Code to process the response and update UI.
	}
};

After the execution of long running operation, the result is set in Message and passed to sendMessage of handler. Handle will extract the response from Message and will process and accordingly update the UI. Since Handler is part of main activity, UI thread will be responsible for updating the UI.

Handler approach works fine, but with increasing number of long operations, Thread needs to be created,  run method needs to be implemented and Handler needs to be created. This can be a bit cumbersome. The Android framework has identified this pattern and has nicely enveloped it into what is called an Android Async Task. Let us look at how it can help simplify things.

Async Task

Android Async Task takes cares of thread management and is the recommended mechanism for performing long running operations.

Let us look at a sample class LongOperation, which extends the AsyncTask below:

private class LongOperation extends AsyncTask<String, Void, String> {

	@Override
	protected String doInBackground(String... params) {
		// perform long running operation operation
		return null;
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(String result) {
		// execution of result of Long time consuming operation
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#onPreExecute()
	 */
	@Override
	protected void onPreExecute() {
	// Things to be done before execution of long running operation. For example showing ProgessDialog
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
	 */
	@Override
	protected void onProgressUpdate(Void... values) {
      // Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
	 }
}

Modify the onClick method as shown below:

public void onClick(View v) {
new LongOperation().execute("");
}

As seen class LongOperation extends AsyncTask and implements 4 methods:

  1. doInBackground: Code performing long running operation goes in this method.  When onClick method is executed on click of button, it calls execute method which accepts parameters and automatically calls doInBackground method with the parameters passed.
  2. onPostExecute: This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method.
  3. onPreExecute: This method is called before doInBackground method is called.
  4. onProgressUpdate: This method is invoked by calling publishProgress anytime from doInBackground call this method.

Overriding onPostExecute, onPreExecute and onProgressUpdate is optional.

Points to remember:

  1. Instance of Async Task needs to be created in UI thread. As shown in onClick method a new instance of LongOperation is created there. Also execute method with parameters should be called from UI thread.
  2. Methods onPostExecute, onPreExecute and onProgressUpdate should not be explicitly called.
  3. Task can be executed only once.

Hope this blog helped you understand Android async task and why it is important in Android application development.

Prashant Thakkar
Prashant Thakkar– Team member – Xoriant Mobile Center of Excellence.

29
Jun

Providing a good user experience is critical to mobile applications. UI Application development in Android requires that you have a good understanding of Layouts. In this blog post, we shall cover all about Android Layouts with code samples.

Android Layout is like a container; all the screen will use either of the one layout and all the view (components) on that screen are part of the layout. The fact that mobile screen is small in size it is very important to properly design the UI.

Let us look at the various layouts offered:

  • Linear Layout

This layout as name says is used to place the views in the linear flow one after the other. We can specify the manner in which view are placed linearly i.e. horizontally or vertically.

Let us have a look at the Linear Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
    	>
 <TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
    	 android:text="First Text View"
    	 />

 <TextView
    	 android:layout_width="fill_parent"
    	 android:layout_height="wrap_content"
    	 android:text="Second Text View"
    	 />
 </LinearLayout>

As shown the above Linear Layout have two Text Views and have orientation set to vertical (android:orientation=“vertical”), hence the two Text Views will be drawn vertically one below the other.

Linear Layout Vertical Orientation

Figure 1: Linear Layout Vertical Orientation

Look at the above XML for Linear Layout, width for layout along with Text View with the layout is set to fill_parent (android:layout_width=“fill_parent”). And since Linear Layout is the top most layout and width set to fill parent it will be stretched to cover entire screen. Similarly both the Text Views also have width set to fill parent, and since they are child to Linear Layout they are stretched to entire screen width.

Now let us change the orientation of linear layout to horizontal (android:orientation=“horizontal”).  Just changing the orientation to horizontal will draw Text View next to each other, but since each of the text view is set to have width as fill parent and by default both are written from left to right (Gravity) only one Text View (First Text View) will be visible. To overcome this set width for both the Text View to wrap_content (android:layout_width=“wrap_content”).

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
    	android:layout_width="fill_parent"
    	android:layout_height="fill_parent"
    	>
<TextView
    		android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:text="First Text View"
      />

    		<TextView
    		android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    	android:text="Second Text View"
    		android:paddingLeft="10px"
    		/>
  </LinearLayout>

Note: Since we have set width for both the Text View as wrap_content, 2nd Text View will start as soon as 1st end. Hence in the above xml we have provided left padding for 2nd Text View in order to have some space between the 2 Text View.

Linear Layout Horizontal Orientation

Figure 2 Linear Layout Horizontal Orientation

  • Table Layout

Using this layout we can place view/components in tabular format.  The best example to understand this layout is Login Screen. Below XML shows Table layout

<?xml version="1.0" encoding="utf-8"?>
<TableLayout android:id="@+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

		<TableRow android:id="@+id/TableRow01">
			<TextView android:id="@+id/TextView01"
			android:text="User Name:"
			android:width="100px"/>

			<EditText android:id="@+id/EditText01"
			android:width="220px"/>
		</TableRow>

		<TableRow android:id="@+id/TableRow02">
			<TextView android:id="@+id/TextView02"
			android:text="Password:"
			/>

			<EditText android:id="@+id/EditText02"
			android:inputType="textPassword"/>
		</TableRow>

		<TableRow android:id="@+id/TableRow03">
			<Button android:id="@+id/Button01"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content" android:text="Login"/>

			<Button android:id="@+id/Button02"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content" android:text="Reset"
			android:width="100px"/>
</TableRow>
</TableLayout>

As shown Table consist of three rows (Table Row) and each row as two views/components. Number of columns in table is determined by the maximum number of components in a single row.

Table Layout

Figure 3 : Table Layout

One more important point to note here is that even after specifying width of Reset button in xml to 100 pixel  (android:width=“100px”), it’s width is same as that of Edit Text. This is because width of Column is determined by the maximum width of the component in that column and here Reset button is same the column as Edit Text which has width set to 220 pixel.

  • Relative Layout

This layout is flexible layout of all. This layout as name suggest allow placing components relative to other component or layout. Let us see at the example

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name:"
android:width="100px"/>
<EditText android:id="@+id/EditText01"
android:layout_width="220px"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/TextView01"
android:layout_below="@+id/RelativeLayout01"
/>

<EditText android:id="@+id/EditText02"
android:layout_width="220px"
android:layout_height="wrap_content"
android:layout_below="@+id/EditText01"
android:layout_alignLeft="@+id/EditText01"
/>

<TextView android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password:"
android:width="100px"
android:layout_below="@+id/EditText01"
android:layout_toLeftOf="@+id/EditText02"
/>

<Button android:text="Login"
android:id="@+id/Button01"
android:layout_width="100px"
android:layout_height="wrap_content"
android:layout_below="@id/EditText02"
android:layout_alignLeft="@id/EditText02"
/>

<Button android:text="Reset"
android:id="@+id/Button02"
android:layout_width="100px"
android:layout_height="wrap_content"
android:layout_below="@id/EditText02"
android:layout_alignRight="@id/EditText02"
/>

</RelativeLayout>

As shown,  EditText 01 has attributes android:layout_toRightOf=“@+id/TextView01″ and android:layout_below=“@+id/RelativeLayout01” for placing Edit Text next to Text View (User Name) . Similarly check EditText02 as attributes android:layout_below=“@+id/EditText01″ and android:layout_alignLeft=“@+id/EditText01″ for placing Edit Text box below the Edit Text 01.

Relative Layout

Figure 4 Relative Layout

  • Absolute Layout

As name suggest this layout is used to place views/components at the exact location on the screen using x and y. Let us see example

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout android:id="@+id/AbsoluteLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
android:id="@+id/EditText01"
android:layout_width="200px" android:layout_height="wrap_content"
android:layout_x="12px"
android:layout_y="12px"/>
<Button android:text="Search"
android:id="@+id/Button01"
android:layout_width="100px" android:layout_height="wrap_content"
android:layout_x="220px"
android:layout_y="12px"/>
</AbsoluteLayout>

Absolute Layout

Figure 5 Absolute Layout

As seen we have specified android:layout_x and android:layout_y for both the components  their by providing the absolute location for the components.

  • Frame Layout

Frame Layout is one of the simplest layouts. It is like a single screen and all the views/components child to this layout will be drawn on same screen anchored to the top left corner of the screen. So it is likely that one view can overall another one and hides it unless it is transparent. Let see the example

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:id="@+id/FrameLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

<ImageView android:id="@+id/ImageView01"
android:src="@drawable/taj_mahal"
android:scaleType="center"
android:layout_width="fill_parent" android:layout_height="fill_parent"/>

<TextView android:text="Taj Mahal"
android:id="@+id/TextView01"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginBottom="20dip"
android:layout_gravity="center_horizontal|bottom"
android:padding="10dip"
android:textColor="#FFFFFF"
android:background="#AA0000"
/>
</FrameLayout>

Frame Layout

Figure 6 Frame Layout

Note: taj_mahal.jpg is in drawable folder

Conclusion

We looked at the basic android layouts and tried to understand them with their respective examples.


Prashant Thakkar
Prashant Thakkar– Team member – Xoriant Mobile Center of Excellence.

, , ,