Understanding The Components of A Screen
Understanding The Components of A Screen
a Screen:
•Activity is the basic unit of an Android application that
displays the UI of your application.
•The activity may contain widgets such as buttons,
labels, textboxes, and so on.
•we define UI using an XML file (for example, the
activity_main.xml file located in the res/layout folder
of your project)
•During runtime, we load the XML UI in the onCreate()
method in our Activity class, using the
setContentView() method of the Activity class as
shown:
@Override
public void onCreate(Bundle
savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
views and viewGroups:
• An activity contains views and ViewGroups.
• A view is a widget that has an appearance on screen
examples of views are buttons, labels, and text
boxes.
android.view.View.
• A view derives from the base class
• One or more views can be grouped into a
ViewGroup.
android.view.ViewGroup
• A ViewGroup derives from the base class
• A ViewGroup (which is itself a special type of
view) provides the layout in which you can
order the appearance and sequence of views.
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="AbhiAndroid"
android:textSize="25sp" android:layout_y="200px"/>
<!--y-coordinate of a text view in Android Studio-->
Table Layout
• In Android, Table Layout is used to arrange the group of views
into rows and columns. Table Layout containers do not
display a border line for their columns, rows or cells. A Table
will have as many columns as the row with the most cells.
• A table can also leave the cells empty but cells can’t span the
columns as they can in HTML.
• Important Points About Table Layout In Android:
• For building a row in a table we will use
the <TableRow> element. Table row objects are the child
views of a table layout.
• Each row of the table has zero or more cells and each cell can
hold only one view object like ImageView, TextView or any
other view.
• Total width of a table is defined by its parent container
• Column can be both stretchable and shrinkable. If shrinkable
then the width of column can be shrunk to fit the table into
its parent object and if stretchable then it can expand in
width to fit any extra space available.
• Important Note: We cannot specify the width of the
children’s of the Table layout. Here, width always match
parent width. However, the height attribute can be defined
by a child; default value of height attribute is wrap content.
TableLayout Attributes
• Following are the important attributes specific to TableLayout
android:id
• This is the ID which uniquely identifies the layout.
android:collapseColumns
• This specifies the zero-based index of the columns to collapse.
The column indices must be separated by a comma: 1, 2, 5.
android:shrinkColumns
• The zero-based index of the columns to shrink. The column
indices must be separated by a comma: 1, 2, 5.
android:stretchColumns
• The zero-based index of the columns to stretch. The column
indices must be separated by a comma: 1, 2, 5.
• <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:background="#000"
android:orientation="vertical" android:stretchColumns="1">
<TableRow android:padding="5dip"> <TextView
android:layout_height="wrap_content"
android:layout_marginBottom="20dp" android:layout_span="2"
android:gravity="center_horizontal" android:text="@string/loginForm"
android:textColor="#0ff" android:textSize="25sp" android:textStyle="bold" />
</TableRow> <TableRow>
<TextView android:layout_height="wrap_content" android:layout_column="0"
android:layout_marginLeft="10dp" android:text="@string/userName"
android:textColor="#fff" android:textSize="16sp" /> <EditText
android:id="@+id/userName" android:layout_height="wrap_content"
android:layout_column="1" android:layout_marginLeft="10dp"
android:background="#fff" android:hint="@string/userName"
android:padding="5dp" android:textColor="#000" />
</TableRow>
<TableRow>
<TextView android:layout_height="wrap_content" android:layout_column="0"
android:layout_marginLeft="10dp" android:layout_marginTop="20dp"
android:text="@string/password" android:textColor="#fff"
android:textSize="16sp" />
<EditText android:id="@+id/password" android:layout_height="wrap_content"
android:layout_column="1" android:layout_marginLeft="10dp"
android:layout_marginTop="20dp" android:background="#fff"
android:hint="@string/password" android:padding="5dp"
android:textColor="#000" />
</TableRow>
<TableRow android:layout_marginTop="20dp"> <Button
android:id="@+id/loginBtn" android:layout_height="wrap_content"
android:layout_gravity="center" android:layout_span="2"
android:background="#0ff" android:text="@string/login"
android:textColor="#000" android:textSize="20sp" android:textStyle="bold" />
</TableRow>
</TableLayout>
• Output:
Relative Layout
• The Relative Layout is very flexible layout used in android for
custom layout designing. It gives us the flexibility to position
our component/view based on the relative or sibling
component’s position.
• Just because it allows us to position the component anywhere
we want so it is considered as most flexible layout.
• For the same reason Relative layout is the most used layout
after the Linear Layout in Android.
• It allow its child view to position relative to each other or
relative to the container or another container.
• In Relative Layout, you can use “above, below, left and right”
to arrange the component’s position in relation to other
component.
RelativeLayout Attributes
Following are the important attributes specific to RelativeLayout
android:id
• This is the ID which uniquely identifies the layout.
android:gravity
• This specifies how an object should position its content, on
both the X and Y axes. Possible values are top, bottom, left,
right, center, center_vertical, center_horizontal etc.
android:ignoreGravity
• This indicates what view should not be affected by gravity.
android:layout_above
• Positions the bottom edge of this view above the given anchor view ID and must be a
reference to another resource, in the form "@[+][package:]type:name"
android:layout_alignBottom
• Makes the bottom edge of this view match the bottom edge of the given anchor view ID and
must be a reference to another resource, in the form "@[+][package:]type:name".
android:layout_alignLeft
• Makes the left edge of this view match the left edge of the given anchor view ID and must be
a reference to another resource, in the form "@[+][package:]type:name".
android:layout_alignParentBottom
• If true, makes the bottom edge of this view match the bottom edge of the parent. Must be a
boolean value, either "true" or "false".
android:layout_alignParentEnd
• If true, makes the end edge of this view match the end edge of the parent. Must be a
boolean value, either "true" or "false".
android:layout_alignParentLeft
• If true, makes the left edge of this view match the left edge of the parent. Must be a boolean
value, either "true" or "false".
android:layout_alignParentRight
• If true, makes the right edge of this view match the right edge of the parent. Must be a
boolean value, either "true" or "false".
android:layout_alignParentStart
• If true, makes the start edge of this view match the start edge of the parent. Must
be a boolean value, either "true" or "false".
android:layout_alignParentTop
• If true, makes the top edge of this view match the top edge of the parent. Must be
a boolean value, either "true" or "false".
android:layout_alignRight
• Makes the right edge of this view match the right edge of the given anchor view ID
and must be a reference to another resource, in the form "@[+]
[package:]type:name".
android:layout_alignStart
• Makes the start edge of this view match the start edge of the given anchor view ID
and must be a reference to another resource, in the form "@[+]
[package:]type:name".
• android:layout_alignTop
• Makes the top edge of this view match the top edge of the given anchor view ID
and must be a reference to another resource, in the form "@[+]
[package:]type:name".
android:layout_below
• Positions the top edge of this view below the given anchor view ID and must be a
reference to another resource, in the form "@[+][package:]type:name".
android:layout_centerHorizontal
• If true, centers this child horizontally within its parent. Must be a boolean value,
either "true" or "false".
android:layout_centerInParent
• If true, centers this child horizontally and vertically within its parent. Must be a
boolean value, either "true" or "false".
android:layout_centerVertical
• If true, centers this child vertically within its parent. Must be a boolean value,
either "true" or "false".
android:layout_toEndOf
• Positions the start edge of this view to the end of the given anchor view ID and
must be a reference to another resource, in the form "@[+][package:]type:name".
android:layout_toLeftOf
• Positions the right edge of this view to the left of the given anchor view ID and
must be a reference to another resource, in the form "@[+][package:]type:name".
android:layout_toRightOf
• Positions the left edge of this view to the right of the given anchor view ID and
must be a reference to another resource, in the form "@[+][package:]type:name".
android:layout_toStartOf
• Positions the end edge of this view to the start of the given anchor view ID and
must be a reference to another resource, in the form "@[+][package:]type:name".
Example
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<!--Text View for Displaying SIGN IN Text At Top of UI-->
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textAppearance="?
android:attr/textAppearanceLarge" android:text="SIGN IN"
android:id="@+id/textView3" android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<!--Text View for Displaying Username-->
<TextView android:id="@+id/userName" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/activity_horizontal_margin"
android:layout_marginTop="110dp" android:text="UserName:"
android:textColor="#000000" android:textSize="20sp" />
<!--Text View for Displaying Password--> <TextView android:id="@+id/password"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_below="@+id/userName"
android:layout_margin="@dimen/activity_horizontal_margin"
android:text="Password:" android:textColor="#000000"
android:textSize="20sp" />
<!--Edit Text for Filling Username--> <EditText android:id="@+id/edt_userName"
android:layout_width="fill_parent" android:layout_height="40dp"
android:layout_marginLeft="@dimen/activity_horizontal_margin"
android:layout_marginTop="100dp" android:layout_toRightOf="@+id/userName"
android:hint="User Name" />
>
<!--Edit Text for Filling Password-->
<EditText android:layout_width="fill_parent" android:layout_height="40dp"
android:layout_below="@+id/edt_userName"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/password" android:hint="Password" />
<!--Button for Clicking after filling details-->
<Button android:id="@+id/btnLogin" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/password"
android:layout_centerHorizontal="true" android:layout_marginTop="20dp"
android:background="#03B424" android:text="Login"
android:textColor="#ffffff" android:textStyle="bold" />
</RelativeLayout>
• Output:
• Difference between Linear And Relative Layout:
• RELATIVE LAYOUT:
• Every element of relative layout arranges itself to the other element or a
parent element.
• It is helpful while adding views one next to other etc
• In a relative layout you can give each child a Layout Property that specifies
exactly where it should go in relative to the parent or relative to other
children.
• Views can be layered on top of each other.
• LINEAR LAYOUT:
• In a linear layout, like the name suggests, all the elements are displayed in
a linear fashion either vertically or horizontally.
• Either Horizontally or Vertically this behavior is set in android:orientation
which is an property of the node Linear
Layout.android:orientation=”horizontal” or android:orientation=”vertical”
• Linear layouts put every child, one after the other, in a line, either
horizontally or vertically.
Frame Layout
• Frame Layout is one of the simplest layout to organize view
controls. They are designed to block an area on the screen.
• Frame Layout should be used to hold child view, because it
can be difficult to display single views at a specific area on the
screen without overlapping each other.
• We can add multiple children to a FrameLayout and control
their position by assigning gravity to each child, using
the android:layout_gravity attribute.
• FrameLayout Attributes
• Following are the important attributes specific to FrameLayout −
android:id
• This is the ID which uniquely identifies the layout.
android:foreground
• This defines the drawable to draw over the content and possible values
may be a color value, in the form of "#rgb", "#argb", "#rrggbb", or
"#aarrggbb".
android:foregroundGravity
• Defines the gravity to apply to the foreground drawable. The gravity
defaults to fill. Possible values are top, bottom, left, right, center,
center_vertical, center_horizontal etc.
android:measureAllChildren
• Determines whether to measure all children or just those in the VISIBLE or
INVISIBLE state when measuring. Defaults to false.
• Example
• <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent" android:layout_width="match_parent" >
• <TextView android:text="LeftTop" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
• <TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="RightTop"
android:layout_gravity="top|right" />
• <TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="CentreTop"
android:layout_gravity="top|center_horizontal" />
• <TextView android:text="Left" android:layout_gravity="left|center_vertical"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
• <TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="Right"
android:layout_gravity="right|center_vertical" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="Centre"
android:layout_gravity="center" />
<TextView android:text="LeftBottom" android:layout_gravity="left|bottom"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="RightBottom"
android:layout_gravity="right|bottom" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="CenterBottom"
android:layout_gravity="center|bottom" />
</FrameLayout>
Output:
Scroll View
• A ScrollView is a special type of FrameLayout in that it
enables users to scroll through a list of views that occupy
more space than the physical display.
• The ScrollView can contain only one child view or ViewGroup,
which normally is a LinearLayout.
• Example:
<ScrollView
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
<LinearLayout
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:orientation=”vertical” >
<Button
android:id=”@+id/button1”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Button 1” />
<Button
android:id=”@+id/button2”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Button 2” />
<Button
android:id=”@+id/button3”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Button 3” />
</LinearLayout>
</ScrollView>
Adapting to Display Orientation
• Android supports two screen orientations: portrait and landscape.
• By default, when you change the display orientation of your Android
device, the current activity that is displayed automatically redraws its
content in the new orientation.
• This is because the onCreate() method of the activity is fi red whenever
there is a change in display orientation.
• In general, you can employ two techniques to handle changes in screen
orientation:
• Anchoring — The easiest way is to “anchor” your views to the four edges
of the screen. When the screen orientation changes, the views can anchor
neatly to the edges.
• Resizing and repositioning — Whereas anchoring and centralizing are
simple techniques to ensure that views can handle changes in screen
orientation, the ultimate technique is resizing each and every view
according to the current screen orientation.
Anchoring Views
• Anchoring can be easily achieved by using RelativeLayout.
Consider the following main.xml file, which contains five
Button views embedded within the <RelativeLayout>
element:
<RelativeLayout
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android”>
<Button
android:id=”@+id/button1”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Top Left”
android:layout_alignParentLeft=”true”
android:layout_alignParentTop=”true” />
<Button
android:id=”@+id/button2”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Top Right”
android:layout_alignParentTop=”true”
android:layout_alignParentRight=”true” />
<Button
android:id=”@+id/button3”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Bottom Left”
android:layout_alignParentLeft=”true”
android:layout_alignParentBottom=”true” />
<Button
android:id=”@+id/button4”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Bottom Right”
android:layout_alignParentRight=”true”
android:layout_alignParentBottom=”true” />
<Button
android:id=”@+id/button5”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Middle”
android:layout_centerVertical=”true”
android:layout_centerHorizontal=”true” />
</RelativeLayout>
➤layout_alignParentLeft — Aligns the view to the left of the
parent view
➤ layout_alignParentRight — Aligns the view to the right of the
parent view
➤ layout_alignParentTop — Aligns the view to the top of the
parent view
➤ layout_alignParentBottom — Aligns the view to the bottom of
the parent view
➤ layout_centerVertical — Centers the view vertically within its
parent view
➤ layout_centerHorizontal — Centers the view horizontally
within its parent view
• Output:
Resizing and Repositioning
• Apart from anchoring your views to the four edges of the screen, an
easier way to customize the UI based on screen orientation is to create a
separate res/layout folder containing the XML files for the UI of each
orientation.
• To support landscape mode, you can create a new folder in the res folder
and name it as layout-land (representing landscape). Basically, the
main.xml file contained within the layout folder defines the UI for the
activity in portrait mode, whereas the main.xml file in the layout-land
folder defines the UI in landscape mode.
MANAGING CHANGES TO SCREEN ORIENTATION
• Understanding Activity Behavior When Orientation Changes
• Example:
1. Using Android Studio, create a new Android project and name it Orientations.
2. Add the following statements in bold to the Activity_main.xml file:
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<EditText
android:id=”@+id/txtField1”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content” />
<EditText
android:layout_width=”fill_parent”
android:layout_height=”wrap_content” />
</LinearLayout>
Add the following statements in bold to the OrientationsActivity.java fi le:
package net.learn2develop.Orientations;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class OrientationsActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d(“StateInfo”, “onCreate”);
}
@Override
public void onStart() {
Log.d(“StateInfo”, “onStart”);
super.onStart();
}
@Override
public void onResume() {
Log.d(“StateInfo”, “onResume”);
super.onResume();
}
@Override
public void onPause() {
Log.d(“StateInfo”, “onPause”);
super.onPause();
}
@Override
public void onStop() {
Log.d(“StateInfo”, “onStop”);
super.onStop();
}
@Override
public void onDestroy() {
Log.d(“StateInfo”, “onDestroy”);
super.onDestroy();
}
@Override
public void onRestart() {
Log.d(“StateInfo”, “onRestart”);
super.onRestart();
}
}
4.Press Shift+F9 to debug the application on the android emulator.
5.Enter some text into the two EditText views.
6. Change the orientation of the Android Emulator by pressing Ctrl+left.
• Output:
• You can also programmatically remove the Action Bar using the ActionBar
class. To do so, you first need to remove the android:theme attribute you
added in the previous step. This is important, otherwise the next step will
cause the application to raise an exception.
• Modify the MyActionBarActivity.java file as follows:
package net.learn2develop.MyActionBar;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
public class MyActionBarActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActionBar actionBar = getActionBar();
actionBar.hide();
//actionBar.show(); //---show it again---
} }
• debug the application on the emulator again. The Action Bar remains
hidden.
Adding Action Items to the Action Bar
• Using the MyActionBar project created in the previous section, add the following
code in bold to the MyActionBarActivity.java file:
package net.learn2develop.MyActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MyActionBarActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//ActionBar actionBar = getActionBar();
//actionBar.hide();
//actionBar.show(); //---show it again---
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
CreateMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
return MenuChoice(item);
}
private void CreateMenu(Menu menu)
{
MenuItem mnu1 = menu.add(0, 0, 0, “Item 1”);
{
mnu1.setIcon(R.drawable.ic_launcher);
mnu1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
MenuItem mnu2 = menu.add(0, 1, 1, “Item 2”);
{
mnu2.setIcon(R.drawable.ic_launcher);
mnu2.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
MenuItem mnu3 = menu.add(0, 2, 2, “Item 3”);
{
mnu3.setIcon(R.drawable.ic_launcher);
mnu3.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
MenuItem mnu4 = menu.add(0, 3, 3, “Item 4”);
{
mnu4.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
MenuItem mnu5 = menu.add(0, 4, 4, “Item 5”);
{
mnu5.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
}
private boolean MenuChoice(MenuItem item)
{
switch (item.getItemId()) {
case 0:
Toast.makeText(this, “You clicked on Item 1”,
Toast.LENGTH_LONG).show();
return true;
case 1:
Toast.makeText(this, “You clicked on Item 2”,
Toast.LENGTH_LONG).show();
return true;
case 2:
Toast.makeText(this, “You clicked on Item 3”,
Toast.LENGTH_LONG).show();
return true;
case 3:
Toast.makeText(this, “You clicked on Item 4”,
Toast.LENGTH_LONG).show();
return true;
case 4:
Toast.makeText(this, “You clicked on Item 5”,
Toast.LENGTH_LONG).show();
return true;
}
return false;
}
}
• Debug the application on the Android emulator. Observe the icons on the
right side of the Action Bar.
• Clicking each menu item will cause the Toast class to display the name of
the menu item selected.
• Users interact with your UI at two levels: the activity level and the view
level. At the activity level, the Activity class exposes methods that you can
override.
• Some common methods that you can override in your activities include
the following:
onKeyDown — Called when a key was pressed and not handled by any of the
views contained within the activity
onKeyUp — Called when a key was released and not handled by any of the
views contained within the activity
onMenuItemSelected — Called when a panel’s menu item has been selected
by the user.
onMenuOpened — Called when a panel’s menu is opened by the user
Overriding Methods Defi ned in an Activity
• create a new Android project and name it UIActivity.
• Add the following sttements in bold to main.xml (replacing the TextView)
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<TextView
android:layout_width=”214dp”
android:layout_height=”wrap_content”
android:text=”Your Name” />
<EditText
android:id=”@+id/txt1”
android:layout_width=”214dp”
android:layout_height=”wrap_content” />
<Button
android:id=”@+id/btn1”
android:layout_width=”106dp”
android:layout_height=”wrap_content”
android:text=”OK” />
<Button
android:id=”@+id/btn2”
android:layout_width=”106dp”
android:layout_height=”wrap_content”
android:text=”Cancel” />
</LinearLayout>
• Add the following statements in bold to the UIActivityActivity.java file:
import android.view.KeyEvent;
import android.widget.Toast;
public class UIActivityActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_DPAD_CENTER:
Toast.makeText(getBaseContext(),
“Center was clicked”,
Toast.LENGTH_LONG).show();
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
Toast.makeText(getBaseContext(),
“Left arrow was clicked”,
Toast.LENGTH_LONG).show();
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
Toast.makeText(getBaseContext(),
“Right arrow was clicked”,
Toast.LENGTH_LONG).show();
break;
case KeyEvent.KEYCODE_DPAD_UP:
Toast.makeText(getBaseContext(),
“Up arrow was clicked”,
Toast.LENGTH_LONG).show();
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
Toast.makeText(getBaseContext(),
“Down arrow was clicked”,
Toast.LENGTH_LONG).show();
break;
}
return false;
}
• debug the application on the Android emulator.
• When the activity is loaded, type some text into the EditText. Next, click
the down arrow key on the directional pad. Observe the message shown
on the screen.
• Output:
Registering Events for Views
• Views can fire events when users interact with them. For example, when a
user touches a Button view, you need to service the event so that the
appropriate action can be performed.
• To do so, you need to explicitly register events for views.
package net.learn2develop.UIActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class UIActivityActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//---the two buttons are wired to the same event handler---
Button btn1 = (Button)findViewById(R.id.btn1);
btn1.setOnClickListener(btnListener);
Button btn2 = (Button)findViewById(R.id.btn2);
btn2.setOnClickListener(btnListener);
}
//---create an anonymous class to act as a button click listener---
private OnClickListener btnListener = new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(getBaseContext(),
((Button) v).getText() + “ was clicked”,
Toast.LENGTH_LONG).show();
}
};
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//...
}
}
• If you now click either the OK button or the Cancel button, the
appropriate message will be displayed.
• Output: