- Back to Home »
- TableLayout
Posted by : Unknown
Friday, August 23, 2013
Hi everyone! For this post, I am going to keep working with
the different layouts. On my previous post, I tried out the Grid View layout.
Now, I am going to work with the layout called TableLayout. I am going to
create a new Android application project named ContactInformation. I will use
it to learn about the TableLayout by creating a basic form. The application
will also respond to a button and display the user input. This will be the
result:
Contact Information Application |
The class TableLayout is one of the subclasses of the class
ViewGroup found in the package android.view. The package provides classes for
the user interface which includes screen layouts and ways for the user to
interact with them. The user interface that you design can have more than one
layout nested within another layout.
The class TableLayout allows objects to be arranged into
rows and columns. The rows are defined by the class TableRow. The TableRow
layout extends LinearLayout and it arranges objects horizontally. If a TableRow
object is not used with a TableLayout object, the TableRow object will act as a
LinearLayout with horizontal orientation. The width attribute of a TableRow
object should be match_parent and the height attribute should be
wrap_content.
In a TableLayout, the rows have cells. The cells are added to each row in increasing column order. If a column order is skipped, that cell is set as empty. Each cell can have
a View object. Some View object examples
are text views and buttons. The number of columns in a TableLayout depends on
the row with the most number of cells and the width of the column depends on
the widest cell in that column. By using the XML attribute android:stretchColumns
or the method setStretchAllColumns(boolean), all columns can be set as
stretchable. By using the XML attribute android:shrinkColumns or the method
setShrinkAllColumns(boolean), all columns can be set as shrinkable. By using
the methods setColumnShrinkable(int columnIndex, boolean) or setColumnStretchable(int
columnIndex, boolean), a specific column can be set shrinkable or stretchable
respectively. A column set as stretchable can stretch in width to fit any extra
space and a column set as shrinkable can shrink to fit the table. A column can
be set to hide by calling the method setColumnCollapsed(int, boolean) or using
the XML attribute android: collapseColumns.
Let us start by creating a new Android application project
named ContactInformation. Go to File in the main menu and select New ->
Other. The wizard will start. Select Android Application Project found in the
Android folder and click Next.
Eclipse New Android Application Project |
In the New Android Application window, I filled
it out with the following fields and clicked Next:
- Application Name: Contact Infomation
- Project Name: ContactInformation
- Package Name: com.android.contactinformation
- Minimum Required SDK: API 8: Android 2.2 (Froyo)
- Target SDK: API 17: Android 4.2 (Jelly Bean)
- Compile With: API 18: Android 4.3
- Theme: Holo Light with Dark Action Bar
Eclipse New Android Application Project |
In the following window, select the checkboxes to create a
custom launcher icon, to create an activity, and to create project in
workspace.
Eclipse New Android Application Project |
Configure the launcher icon any way you like. For my launcher icon,
I chose the following and clicked Next:
- Foreground: Clipart
- Selected Trim Surrounding Blank Space checkbox
- Additional Padding: 24%
- Foreground Scaling: Center
- Shape: Square
- Background Color: Dark green
- Foreground Color: Light green
Eclipse Configure Launcher Icon |
In the next window, select the checkbox to create an
activity and select Blank Activity. Click Next. In the Blank Activity window, I
left the default values which are:
- Activity Name: MainActivity
- Layout Name: activity_main
- Navigation Type: None
Click Finish and wait for Eclipse to create the project.
After Eclipse is done, you can see the project ContactInformation in the
Project Explorer and the file activity_main.xml opened in the Graphical Layout.
activity_main.xml Graphical Layout |
As you can see, the application is displaying the string “Hello
world!” and the file activity_main.xml looks like this:
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
Modify the activity_main.xml file to the following:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:stretchColumns="1"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
</TableLayout>
As you can see, the layout was changed from RelativeLayout
to TableLayout, the width of the layout was set to match_parent, and the height
of the layout was set to fill_parent. The XML attribute android:stretchColumns
was set to 1, so all columns are set to stretchable. Now, let us add a TableRow
to the TableLayout:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:stretchColumns="1"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TableRow
android:paddingBottom="10dp">
<TextView
android:text="@string/first_name" />
<EditText
android:id="@+id/first_name"
android:inputType="text"
android:hint="@string/hint_first_name" />
</TableRow>
</TableLayout>
In this TableRow, a padding at the bottom is set to 10dp by
using the XML attribute android:paddingBottom. This means there would be space
underneath the TableRow. First, a TextView is created with the string resource
named first_name, which will be created shortly. You should be seeing an error
right now, but when the string resource is added it will fixed. Then, a
user-editable text field is created using the <EditText> tag. In this
EditText, an id named first_name is assigned as identifier for this view. An
identifier is needed, so we can later get what the user wrote. By using the
XML attribute android:inputType, the EditView type is set to value text. This
means the content type of the EditText will be text. Finally, by using the XML
attribute android:hint, a hint for the user is set. This means the string
resource named hint_first_name, which will be added soon, will be displayed on the
text field as a hint on what the user should type.
The form will contain text fields for the first name, middle
name, last name, phone, address, and email. Let us add the string resources
needed for the text fields. To do this, there are two ways. You can add the
string resources using the interface. The interface of the strings.xml file can
be found under the res->values folder in the Resources tab.
strings.xml Resources |
To add a new
resource, click Add. Select String in the new window and click Ok. On the right
side, where it says Attributes for String, enter first_name for the Name field
and First Name: for the Value field and save the project.
strings.xml |
You should now see
the string resource first_name on the list. You can delete the hello_world
resource by clicking Remove because it will not be needed. You can use this method to add all the string resources that
we are going to be using for the project or you can create them by adding each
of them directly to the strings.xml file by clicking the tab.
strings.xml |
The final strings.xml
file will be:
<?xml version="1.0"
encoding="utf-8"?>
<resources>
<string name="app_name">Contact Information</string>
<string name="action_settings">Settings</string>
<string name="first_name">First Name:</string>
<string name="hint_first_name">Enter First Name</string>
<string name="middle_name">Middle Name:</string>
<string name="hint_middle_name">Enter Middle Name</string>
<string name="last_name">Last Name:</string>
<string name="hint_last_name">Enter Last Name</string>
<string name="phone">Phone:</string>
<string name="hint_phone">Enter Phone Number</string>
<string name="address">Address:</string>
<string name="hint_address">Enter Address</string>
<string name="email">Email:</string>
<string name="hint_email">Enter Email</string>
<string name="button_send">Send</string>
</resources>
As you can see, a text and hint were created for each text
field. Also, a string resource named button_save was created for a button. Now
that we have all the string resources needed, let’s go back to the activity_main.xml
file to modify it. This would be the final activity_main.xml file:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="1"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TableRow
android:paddingBottom="10dp">
<TextView
android:text="@string/first_name" />
<EditText
android:id="@+id/first_name"
android:inputType="text"
android:hint="@string/hint_first_name" />
</TableRow>
<TableRow
android:paddingBottom="10dp">
<TextView
android:text="@string/middle_name" />
<EditText
android:id="@+id/middle_name"
android:inputType="text"
android:hint="@string/hint_middle_name" />
</TableRow>
<TableRow
android:paddingBottom="10dp">
<TextView
android:text="@string/last_name" />
<EditText
android:id="@+id/last_name"
android:inputType="text"
android:hint="@string/hint_last_name" />
</TableRow>
<TableRow
android:paddingBottom="10dp">
<TextView
android:text="@string/phone" />
<EditText
android:id="@+id/phone"
android:inputType="phone"
android:hint="@string/hint_phone" />
</TableRow>
<TableRow
android:paddingBottom="10dp">
<TextView
android:text="@string/address" />
<EditText
android:id="@+id/address"
android:inputType="textMultiLine"
android:hint="@string/hint_address" />
</TableRow>
<TableRow
android:paddingBottom="40dp">
<TextView
android:text="@string/email" />
<EditText
android:id="@+id/email"
android:inputType="textEmailAddress"
android:hint="@string/hint_email" />
</TableRow>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendInformation" />
</TableLayout>
As you can see, a TableRow is added for each text field
which will contain a TextView and an EditText. Also, the inputType is set to
text except for address, which is set to textMultiLine, and phone, which is set
to phone inputType. At the end, a button is added with the string resource name
button_save created earlier. By using the XML attribute android:onClick for the
button, the name of the method can be set. In this case, it is set to sendInformation.
This is the name of the method that will be invoked when the button is clicked
and it will be implemented soon.
To be able to respond to the Send button, we need to implement
the method sendInformation() on the Main_Activity.java file found under src
folder. Add the following code after the onCreateOptionMenu():
public void sendInformation(View
view) {
Intent intent = new Intent(this
, DisplayInformationActivity.class);
EditText editText = (EditText)
findViewById(R.id.first_name);
String firstName =
editText.getText().toString();
editText = (EditText) findViewById(R.id.middle_name);
String middleName =
editText.getText().toString();
editText = (EditText) findViewById(R.id.last_name);
String lastName =
editText.getText().toString();
editText = (EditText) findViewById(R.id.phone);
String phone =
editText.getText().toString();
editText = (EditText) findViewById(R.id.address);
String address =
editText.getText().toString();
editText = (EditText) findViewById(R.id.email);
String email =
editText.getText().toString();
String info = "First Name:
" +
firstName + "\n" +
"Middle Name: " + middleName + "\n" +
"Last Name: " + lastName + "\n" +
"Phone: " + phone + "\n" +
"Address: \n" + address + "\n" +
"Email: " + email + "\n";
intent.putExtra(EXTRA_MESSAGE, info);
startActivity(intent);
}
The method sendInformation(View) is invoked when the user
clicks on the Send button.
Next, an Intent object is initialized. An Intent
object provides runtime binding between separate components. In our case, it
will be used to start another activity. The Intent constructor has two
parameters, the Context and the Class. Because Activity is a subclass of
Context, this is used as the first parameter. DisplayInformationActivity.class
is used as the second parameter. You should see an error right now, but this
class will be created soon and the error will be fixed. The intent will be
deliver to this class.
Next, an EditText object is initialized and, by using the
method findViewById(), the text field is assigned to the new EditText object.
A new
String object named info is initialized to get the text in the field by using the methods
getText() and toString() on the EditText object.
Finally, the method putExtra()
is used on the Intent object. An Intent object can carry data types as
key-value pairs called extras. The method putExtra() has two parameters. The
first parameter is the key name, which in this case is EXTRA_MESSAGE and the
second parameter is the value, which in this case is the String object named
info. The String object info contains a String chain of all the text found on
the text fields.
Add the EXTRA_MESSAGE definition in the beginning of the
MainActivity.java class:
public final static
String EXTRA_MESSAGE = "com.android.contactinformation.MESSAGE";
The package is used as a prefix to ensure the key is unique
and will be able to interact with other apps.
Now, we will create the DiplayInformationActivity.java
class. In the main menu, select File->New->Other. Select Android Activity and click Next.
Eclipse Android Activity |
On the next window,
select BlankActivity and click Next. Enter the following for the Blank Activity
and click Finish:
- Project: ContactInformation
- Activity Name: DisplayInformationActivity
- Layout Name: activity_display_information
- Title: Contact Information
- Launcher Activity: Unchecked
- Hierarchical Parent: android.contactinformation.MainActivity
- Navigation Type: None
As you can see in the Project Explorer, a new activity was
added in the package com.android.contactinformation named DisplayInformationActivity.java and a new layout file named activity_display_information.xml was added to the
layout folder. Go to the DisplayInformationActivity.java file. The file should
look like this:
package
com.android.contactinformation;
import android.os.Bundle;
import
android.app.Activity;
import android.view.Menu;
import
android.view.MenuItem;
import
android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.os.Build;
public class
DisplayInformationActivity extends Activity {
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_information);
// Show the Up
button in the action bar.
setupActionBar();
}
/**
* Set up the {@link android.app.ActionBar}, if the API is
available.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >=
Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean
onCreateOptionsMenu(Menu menu) {
// Inflate the
menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_information, menu);
return true;
}
@Override
public boolean
onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID
represents the Home or Up button. In the case of this
// activity, the Up
button is shown. Use NavUtils to allow users
// to navigate up
one level in the application structure. For
// more details,
see the Navigation pattern on Android Design:
//
//
http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
You will see Eclipse has implemented three methods. The new
method onOptionsItemSelected(MenuItem) allows users to navigate up one level.
To use the ActionBar, version code HONEYCOMB is needed. You can see Eclipse
adds a condition for the getActionBar() method to check the version code.
To receive the intent, add the following code on the method
onCreate():
Intent intent = getIntent();
String info = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
To display the information, add the following code after
that:
TextView textView = new TextView(this);
textView.setTextSize(20);
textView.setText(info);
To set the TextView object as the activity layout, add the following
code after that:
setContentView(textView);
To test the application, right click the project folder on
the Project Explorer and select Run As->Android Application. Wait for
Eclipse to launch the application. It might take a while if you are starting
the emulator.
Contact Information - Emulator |
Contact Information - Emulator |
As you can see, they keyboard changed to numbers in the phone text field because the inputType was set to "phone".
Contact Information - Emulator |
As you can see, the address text field can have multiple lines because the inputType was set to "textMultiLines". When you are finish click the Send button.
Contact Information - Emulator |
The result is:
Contact Information - Emulator |
You can click the Up button to enter a new contact information. However, the data will not be saved. To save the data, some of the options are SQLite database or an external storage which will be covered in a future post.
Thank you for reading. Feel free to leave comments, subscribe, or
follow me on Google+. If you have any questions about any tutorials found on my blog, feel free to leave a comment on the facebook page and I will do my best to help you.