0% found this document useful (0 votes)
155 views

Understanding The Components of A Screen

The document discusses the components of an Android screen. It explains that an activity displays the user interface and contains views and view groups. Views are widgets like buttons and labels, while view groups arrange views visually. Common view groups include linear layouts, which arrange views vertically or horizontally, and relative layouts, which position views relative to each other. The document provides details on different types of layouts and their attributes.

Uploaded by

Farhaan Mohammed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
155 views

Understanding The Components of A Screen

The document discusses the components of an Android screen. It explains that an activity displays the user interface and contains views and view groups. Views are widgets like buttons and labels, while view groups arrange views visually. Common view groups include linear layouts, which arrange views vertically or horizontally, and relative layouts, which position views relative to each other. The document provides details on different types of layouts and their attributes.

Uploaded by

Farhaan Mohammed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 82

Understanding the components of

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.

• Examples of ViewGroups include


RadioGroup ,ScrollView and Layout.
Layout:
• A Layout is a container that derives from
android.view.ViewGroup and is used as a
container for other views.
• A Layout is used to group and arrange views
visually on the screen.
• The Layouts available to you in Android are as
follows:
– Linear Layout
– Absolute Layout
– Table Layout
– Relative Layout
– Frame Layout
– Scroll View
Linear Layout
• There are two types of linear layout orientation:
– Vertical
– Horizontal
• As the name specified these two orientations are used to
arrange there child one after the other, in a line, either
vertically or horizontally.
• Vertical:
• In this all the child are arranged vertically in a line one after
the other. In below code snippets we have specified
orientation “vertical” so the childs/views of this layout are
displayed vertically.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Vertical Orientation set -->
<!-- Child Views(In this case 2 Button) are here -->
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Button1"
android:id="@+id/button" android:background="#358a32" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Button2"
android:id="@+id/button2" android:background="#0058b6" />
</LinearLayout>
• Output:
• Horizontal:
• In this all the child are arranged horizontally in a line one after the other.
In below code snippets we have specified orientation “horizontal” so the
childs/views of this layout are displayed horizontally.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="horizontal"> <!-- Horizontal Orientation set --> <!-- Child
Views(In this case 2 Button) are here -->
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Button1"
android:id="@+id/button" android:background="#358a32" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Button2"
android:id="@+id/button2" android:background="#0058b6" />
</LinearLayout>
Output:
• Attributes of linear layout
Following are some attributes of linear layout of Android.
• Id: Unique identifier of layout.
• Orientation: Attribute to set linear layout orientation as
vertical or horizontal.
• Layout_Weight: This attribute assigns “importance” value at
each component.
• Gravity: This attribute shows object position in x-y plan such
as center, right, top, bottom and left.
• Weight_sum: This attribute defines the maximum weighted
sum.
• Divider: draw able to use as a vertical divider between
buttons.
Absolute Layout
• In Android, an Absolute Layout is a layout used to design the
custom layouts. In this layout you can specify the exact
location of its children by using x and y coordinates.
• Important Note 1: Absolute layout are harder to maintain for
different mobile screen sizes than other types of layouts
because we set the exact location of a child view or called
component. The positioning is based on x(top) and y(left)
coordinates and that positioning is not as useful in world of
various screen resolutions(sizes) and aspect ratios.
• Important Note 2: Absolute layout is depreciated in Android
because of the same reason as discussed in above note.
• AbsoluteLayout Attributes

• Following are the important attributes specific to


AbsoluteLayout −
android:id
• This is the ID which uniquely identifies the layout.
android:layout_x
• This specifies the x-coordinate of the view.
android:layout_y
• This specifies the y-coordinate of the view.
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="AbhiAndroid"
android:textSize="25sp" android:layout_x="200px"/>
<!--x-coordinates of a text view in AbsoluteLayout-->

<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:

7.Observe the output in the logcat console


Persisting State Information during Changes in
Configuration
• Changing screen orientation destroys an activity and recreates it.
• When an activity is recreated, its current state may be lost.
• When an activity is killed, it will fire one or both of the following two
methods:
➤ onPause() — This method is always fired whenever an activity is killed or
pushed into the background.
➤ onSaveInstanceState() — This method is also fired whenever an activity is
about to be killed or put into the background (just like the onPause()
method). However, unlike the onPause() method, the
onSaveInstanceState() method is not fired when an activity is being
unloaded from the stack (such as when the user pressed the back button),
because there is no need to restore its state later.
• To preserve the state of an activity, you could always implement the
onPause() method, and then use your own ways to preserve the state of
your activity, such as using a database, internal or external file storage, and
so on.
• If you simply want to preserve the state of an activity so that it can be
restored later when the activity is recreated (such as when the device
changes orientation), a much simpler way is to implement the
onSaveInstanceState() method, as it provides a Bundle object as an
argument so that you can use it to save your activity’s state.
• The following code shows that you can save the string ID into the Bundle
object during the onSaveInstanceState() method:
@Override
public void onSaveInstanceState(Bundle outState) {
//---save whatever you need to persist---
outState.putString(“ID”, “1234567890”);
super.onSaveInstanceState(outState);
}
• When an activity is recreated, the onCreate() method is first fired,
followed by the onRestoreInstanceState() method, which enables you to
retrieve the state that you saved previously in the onSaveInstanceState()
method through the Bundle object in its argument:
@ Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//---retrieve the information persisted earlier---
String ID = savedInstanceState.getString(“ID”);
}
• Although you can use the onSaveInstanceState() method to save state
information, note the limitation that you can only save your state
information in a Bundle object. If you need to save more complex data
structures, then this is not an adequate solution.
• Another method that you can use is the
onRetainNonConfigurationInstance() method. This method is fired when
an activity is about to be destroyed due to a configuration change (such as
a change in screen orientation, keyboard availability, etc.). You can save
your current data by returning it in this method, like this:
@Override
public Object onRetainNonConfigurationInstance() {
//---save whatever you want here; it takes in an Object type---
return(“Some text to preserve”);
}
• Note that this method returns an Object type, which allows you to return
nearly any data type. To extract the saved data, you can extract it in the
onCreate() method, using the getLastNonConfigurationInstance() method:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d(“StateInfo”, “onCreate”);
String str = (String) getLastNonConfigurationInstance();
}
• A good use for using the onRetainNonConfigurationInstance() and
getLastNonConfigurationInstance() methods is when you need to persist
some data momentarily, such as when you have downloaded data from a
web service and the user changes the screen orientation. In this scenario,
saving the data using the preceding two methods is much more efficient
than downloading the data again.
Detecting Orientation Changes
• Sometimes you need to know the device’s current orientation during
runtime. To determine that, you can use the WindowManager class. The
following code snippet demonstrates how you can programmatically
detect the current orientation of your activity:
import android.view.Display;
import android.view.WindowManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//---get the current display info---
WindowManager wm = getWindowManager();
Display d = wm.getDefaultDisplay();
if (d.getWidth() > d.getHeight()) {
//---landscape mode---
Log.d(“Orientation”, “Landscape mode”);
}
else {
//---portrait mode---
Log.d(“Orientation”, “Portrait mode”);
}
}
• The getDefaultDisplay() method returns a Display object representing the
screen of the device.
• You can then get its width and height and deduce the current orientation.
Controlling the Orientation of the Activity
• Occasionally, you might want to ensure that your application is displayed
in only a certain orientation.
• For example, you may be writing a game that should be viewed only in
landscape mode. In this case, you can programmatically force a change in
orientation using the setRequestOrientation() method of the Activity
class:
import android.content.pm.ActivityInfo;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//---change to landscape mode---
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
• To change to portrait mode, use the
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT constant.
• Besides using the setRequestOrientation() method, you can also use the
android:screenOrientation attribute on the <activity> element in
AndroidManifest.xml as follows to constrain the activity to a certain
orientation:
<activity
android:label=”@string/app_name”
android:name=”.OrientationsActivity”
android:screenOrientation=”landscape” >
<intent-filter >
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
• Following are two other values that you can
specify in the android:screenOrientation
attribute:
➤ portrait — Portrait mode
➤ sensor — Based on the accelerometer
(default)
UTILIZING THE ACTION BAR
• In place of the traditional title bar located at the top of the
device’s screen, the Action Bar displays the application icon
together with the activity title.
• Optionally, on the right side of the Action Bar are action
items.
Showing and Hiding the Action Bar
• 1.Using Android Studio, create a new Android project and name it
MyActionBar.
• 2. Press F11 to debug the application on the Android emulator. You
should see the application and its Action Bar located at the top of the
screen (containing the application icon and the application name
“MyActionBar”).
• To hide the Action Bar, add the following line in bold to the
AndroidManifest.xml file:
• android:theme=”@android:style/Theme.Holo.NoActionBar” >
• Select the project name in Android and then press F11 to debug the
application on the Android emulator again. This time, the Action Bar is not
displayed .

• 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.

• (Customizing the Action Items and Application Icon)


CREATING THE USER INTERFACE PROGRAMMATICALLY

• Besides using XML you can also create the UI


using code.
• This approach is useful if your UI needs to be
dynamically generated during runtime.
Creating the UI via Code
• create a new Android project and name it UICode.
• In the UICodeActivity.java file, add the following statements
in bold:
package net.learn2develop.UICode;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class UICodeActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
//---param for views---
LayoutParams params =
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
//---create a layout---
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
//---create a textview---
TextView tv = new TextView(this);
tv.setText(“This is a TextView”);
tv.setLayoutParams(params);
//---create a button---
Button btn = new Button(this);
btn.setText(“This is a Button”);
btn.setLayoutParams(params);
//---adds the textview---
layout.addView(tv);
//---adds the button---
layout.addView(btn);
//---create a layout param for the layout---
LinearLayout.LayoutParams layoutParam =
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT );
this.addContentView(layout, layoutParam);
}
}
• Debug the application on the Android emulator.
LISTENING FOR UI NOTIFICATIONS

• 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:

You might also like