0% found this document useful (0 votes)
82 views68 pages

Android Activity Lifecycle Explained

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

Android Activity Lifecycle Explained

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT - II Understanding Activities-Linking Activities Using Intents-

Fragments-Displaying Notifications- Understanding the Components of a


Screen-Adapting to Display Orientation-Managing Changes to Screen
Orientation- Utilizing the Action Bar-Creating the User Interface

UNDERSTANDING ACTIVITIES

This chapter begins by showing you how to create an activity. To create an


activity, you create a Java class that extends the Activity base class:
package [Link].chapter1helloworld;
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
}
Your activity class loads its user interface (UI) component using the XML file
defined in your res/ layout folder. In this example, you would load the UI from the
[Link] file:
setContentView([Link].activity_main);

Every activity you have in your application must be declared in your


[Link] file, like this:
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="[Link]
package="[Link].chapter1helloworld">
<application

android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]"
/>
</intent-filter>
</activity>
</application>
</manifest>
The Activity base class defines a series of events that govern the life cycle of an
activity. Figure 3-1 shows the lifecycle of an Activity.

FIGURE 3-1

The Activity class defines the following events:


 onCreate()—Called when the activity is first created
 onStart()—Called when the activity becomes visible to the user
 onResume()—Called when the activity starts interacting with the user
 onPause()—Called when the current activity is being paused and the
previous activity is being resumed
 onStop()—Called when the activity is no longer visible to the user.
 onDestroy()—Called before the activity is destroyed by the
system (either manually or by the system to conserve
memory)
 onRestart()—Called when the activity has been stopped and is
restarting again
Activities

An activity represents a single screen with a user interface just like a window or frame of
[Link] activity is the subclass of ContextThemeWrapper class.

 An Activity is an application component


 Represents one window, one hierarchy of views
 Typically fills the screen, but can be embedded in other activity or a appear as floating
window
 Java class, typically one activity in one file

What does an Activity do?


 Represents an activity, such as ordering groceries, sending email, or getting directions
 Handles user interactions, such as button clicks, text entry, or login verification
 Can start other activities in the same or other apps
 Has a life cycle—is created, started, runs, is paused, resumed, stopped, and destroyed

Implementing Activities
 Define layout in XML
 Define Activity Java class

extends AppCompatActivity

 Connect Activity with Layout

Set content view in onCreate()

 Declare Activity in the Android manifest


<activity android:name=".MainActivity">

Main Activity needs to include intent to start from launcher icon

1
<activity android:name=".MainActivity">
2
<intent-filter>
3
<action android:name="[Link]" />
4
<category android:name="[Link]" />
5
</intent-filter>
6
</activity>

Activity Lifecycle
 Created (not visible yet)
 Started (visible)
 Resume (visible)
 Paused (partially invisible)
 Stopped (hidden)
 Destroyed (gone from memory)
State changes are triggered by user action, configuration changes such as device rotation, or
system action

onCreate(Bundle savedInstanceState)—static initialization

onStart( )—when activity (screen) is becoming visible

onRestart( )—called if activity was stopped (calls onStart())

onResume( )—start to interact with user

onPause( )—about to resume PREVIOUS activity

onStop( )—no longer visible, but still exists and all state info preserved

onDestroy( )—final call before Android system destroys activity

 onCreate( ) –> Created


 Called when the activity is first created, for example when user taps launcher icon
 Does all static setup: create views, bind data to lists, ...
 Only called once during an activity's lifetime
 Takes a Bundle with activity's previously frozen state, if there was one
 Created state is always followed by onStart()

 onStart( ) –> Started


 Called when the activity is becoming visible to user
 Can be called more than once during lifecycle
 Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes
hidden

1
@Override
2
protected void onStart() {
3
[Link]();
4
// The activity is about to become visible.
5
}
 onRestart( ) –> Started
 Called after activity has been stopped, immediately before it is started again Transient
state
 Always followed by onStart()

1
@Override
2
protected void onRestart() {
3
[Link]();
4
// The activity is between stopped and started.
5
}
 onResume( ) –> Resumed/Running
 Called when activity will start interacting with user
 Activity has moved to top of the activity stack
 Starts accepting user input
 Running state
 Always followed by onPause()

1
@Override
2
protected void onResume() {
3
[Link]();
4
// The activity has become visible
5
// it is now "resumed"
6
}
 onPause( ) –> Paused
 Called when system is about to resume a previous activity
 The activity is partly visible but user is leaving the activity
 Typically used to commit unsaved changes to persistent data, stop animations and
anything that consumes resources
 Implementations must be fast because the next activity is not resumed until this method
returns
 Followed by either onResume() if the activity returns back to the front, or onStop() if it
becomes invisible to the user
1
@Override
2
protected void onPause() {
3
[Link]();
4
// Another activity is taking focus
5
// this activity is about to be "paused"
6
}

 onStop( ) –> Stopped


 Called when the activity is no longer visible to the user
 New activity is being started, an existing one is brought in front of this one, or this one is
being destroyed
 Operations that were too heavy-weight for onPause
 Followed by either onRestart() if this activity is coming back to interact with the user, or
onDestroy() if this activity is going away
1
@Override
2
protected void onStop() {
3
[Link]();
4
// The activity is no longer visible
5
// it is now "stopped"
6
}
 onDestroy( ) –> Destroyed
 Final call before activity is destroyed
 User navigates back to previous activity, or configuration changes
 Activity is finishing or system is destroying it to save space
 Call isFinishing() method to check
 System may destroy activity without calling this, so use onPause() or onStop() to save
data or state
1
@Override
2
protected void onDestroy() {
3
[Link]();
4
// The activity is about to be destroyed.
5
}

TRY IT OUT Understanding the Life Cycle of an Activity ([Link])


1. Using Android Studio, create a new Android project and name it Activity101.
2. In the [Link] file, add the following highlighted statements.
(Please note: Throughout this example, be sure to change all references to
"[Link]" to whatever package name your project is using.)
package [Link].activity101;

import
[Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity


{
String tag = "Lifecycle Step";
@Override
protected void onCreate(Bundle savedInstanceState)
{
[Link](savedInstanceState);
setContentView([Link].activity_main);
Log.d(tag, "In the onCreate() event");
}

public void onStart()


{
[Link]();
Log.d(tag, "In the onStart() event");
}

public void onRestart()


{
[Link]();
Log.d(tag, "In the onRestart() event");
}

public void onResume()


{
[Link]();
Log.d(tag, "In the onResume() event");
}

public void onPause()


{
[Link]();
Log.d(tag, "In the onPause() event");
}

public void onStop()

[Link]();

Log.d(tag, "In the onStop() event");

public void onDestroy()

[Link]();

Log.d(tag, "In the onDestroy() event");

}
}
3. Press Shift+F9 to debug the application, or select Run ➪ Debug. Then select
one of your Android Virtual Devices from the pop-up window.
4. When the activity is first loaded, you should see something very similar to the
following in the logcat console (see Figure 3-3). If you do not see the logcat
console, click Android Monitor at the bottom of the Android Studio window:
11-16 [Link].396: D/Lifecycle Step(559): In the onCreate()
event 11-16 [Link].396: D/Lifecycle Step(559): In the onStart()
event 11-16 [Link].396: D/Lifecycle Step(559): In the
onResume() event

FIGURE 3-3

5. If you click the Back button on the Android emulator, you see the following:
11-16 [Link].665: D/Lifecycle Step(559): In the onPause()
event 11-16 [Link].465: D/Lifecycle Step(559): In the
onStop() event
11-16 [Link].465: D/Lifecycle Step(559): In the onDestroy() event

6. Click the Home button, click the Overview icon, select the Activity101
application, and observe the following:
11-16 [Link].905: D/Lifecycle Step(559): In the onCreate()
event 11-16 [Link].905: D/Lifecycle Step(559): In the onStart()
event 11-16 [Link].925: D/Lifecycle Step(559): In the
onResume() event

7. Click the Home button and then click the Phone button on the Android
emulator so that the activity is pushed to the background. Observe the
output in the logcat window:
11-16 [Link].585: D/Lifecycle Step(559): In the onPause()
event 11-16 [Link].015: D/Lifecycle Step(559): In the
onStop() event

8. Notice that the onDestroy() event is not called, indicating that the activity is still
in memory. Exit the phone dialer by clicking the Back button. The activity is now visible
again. Observe the output in the logcat window:
11-16 [Link].515: D/Lifecycle(559): In the onRestart() event
11-16 [Link].515: D/Lifecycle(559): In the onStart() event
11-16 [Link].515: D/Lifecycle(559): In the onResume()
event
The onRestart() event is now fired, followed by the onStart() and onResume() methods.

How It Works
As you can see from this simple example, an activity is destroyed when you click
the Back button. This is crucial to understand because whatever state the activity is
currently in will be lost. This means
you need to write additional code in your activity to preserve its state when the activity
is destroyed (Chapter 4 shows you how). At this point, note that the onPause() method
is called in both scenarios:
➤ When an activity is sent to the background
➤ When a user kills an activity by tapping the Back button
When an activity is started, the onStart() and onResume()methods are always called,
regardless of whether the activity is restored from the background or newly
created. When an activity is created for the first time, the onCreate() method is
called.
From the preceding example, you can derive the following guidelines:
➤ Use the onCreate() method to create and instantiate the objects that you will
be using in your application.
➤ Use the onResume() method to start any services or code that needs to run
while your activity is in the foreground.
➤ Use the onPause() method to stop any services or code that does not need
to run when your activity is not in the foreground.
➤ Use the onDestroy() method to free up resources before your activity is destroyed.

NOTE Even if an application has only one activity and the activity is
killed, the application is still running in memory.
Applying Styles and Themes to an Activity
By default, an activity is themed to the default Android theme. However,
there has been a push in recent years to adopt a new theme known as
Material. The Material theme has a much more modern and clean look to it.

There are two versions of the Material theme available to Android developers:
Material Light and Material Dark. Either of these themes can be applied from
the [Link].
To apply one of the Material themes to an activity, simply modify the
<Application> element in the [Link] file by changing the default
android:theme attribute. (Please be sure to change all instances of
"[Link]" to whatever package name your project is using.)
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="[Link]
xmlns:tools="[Link]
package="[Link].activity101">

<application

android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@android:style/Theme.
Material">
<activity android:name=".MainActivity">

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Changing the default theme to @android:style/[Link], as in the highlighted


code in the preceding snippet, applies the Material Dark theme and gives your
application a darker look
as shown in Figure 3-4.
Hiding the Activity Title
You can also hide the title of an activity if desired (such as when you just want to
display a status update to the user). To do so, use the requestWindowFeature()
method and pass it the Window
.FEATURE_NO_TITLE constant, like this:
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
requestWindowFeature([Link]
E_NO_TITLE);
}
}

Now you need to change the theme in the [Link] to a theme that has
no title bar. Be sure to change all instances of "[Link]" to whatever package
name your project is using.

package [Link].activity101;

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

<manifest xmlns:android="[Link]
xmlns:tools="[Link]
package="[Link].activity101">
<application

android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@android:style/[Link]"
>
<activity android:name=".MainActivity">

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />


</intent-filter>

</activity>

</application>

</manifest>

This hides the title bar, as shown in Figure 3-5.

FIGURE 3-5

Displaying a Dialog Window


There are times when you need to display a dialog window to get a
confirmation from the user. In this case, you can override the onCreateDialog()
protected method defined in the Activity base class to display a dialog
window. The following Try It Out shows you how.

TRY IT OUT Displaying a Dialog Window Using an Activity ([Link])


1. Using Android Studio, create a new Android project and name it Dialog. When
presented with the option, name the main activity DialogActivity.
2. Add the following theme in bold to the [Link] file. Be sure to
change all instances of "[Link]" to whatever package name your project
is using.
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="[Link]
package="[Link]"
<application

android:allowBackup="true"
android:icon="@mipmap/ic_launcher
"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
>
<activity
android:name=".DialogActivity"
android:label="@string/app_name"
android:theme="@style/[Link]" >
<intent-filter>
<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

3. Compare your [Link] file to this:


package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class DialogActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_dialog);
Toolbar toolbar = (Toolbar) findViewById([Link]);
setSupportActionBar(toolbar);

FloatingActionButton fab = (FloatingActionButton) findViewById([Link]);


[Link](new [Link]() {
@Override
public void onClick(View view) {

[Link](view, "Replace with your own


action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}

});

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_dialog, menu);
return true;
}

@Override

public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in [Link].


int id = [Link]();

//noinspection SimplifiableIfStatement
if (id == [Link].action_settings) {
return true;
}
return [Link](item);

4. Press Shift+F9 to debug the application on the Android emulator. Click


the button to display the dialog (see Figure 3-6).
FIGURE 3-6
Displaying a Progress Dialog
One common UI feature in an Android device is the “Please wait” dialog that
you typically see when an application is performing a long-running task. For
example, the application might be logging in to a server before the user is
allowed to use it, or it might be doing a calculation before displaying the result
to the user. In such cases, it is helpful to display a dialog, known as a progress
dialog, so that the user is kept in the loop.
Android provides a ProgressDialog class you can call when you want to display
a running meter to the user. ProgressDialog is easy to call from an activity.
The following Try It Out demonstrates how to display such a dialog.

TRY IT OUT Displaying a Progress (Please Wait) Dialog

1. Using the Activity101 project created earlier in this chapter, make sure you are
using the Material theme in the [Link] file. Be sure to change all
instances of "[Link]" to whatever package name your project is using.
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="[Link]
xmlns:tools="[Link]
package="[Link].activity101">
<application

android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@android:style/Theme.
Material">
<activity android:name=".MainActivity">
<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>
2. Add the bolded statements from the following code to the [Link] file:
package [Link].activity101;
import [Link];
import
[Link];
import
[Link];
import [Link];
public class MainActivity extends Activity {

ProgressDialog progressDialog;

@Override

protected void onCreate(Bundle savedInstanceState) {


[Link](savedInstanceState);
setContentView([Link].activity_main);
}

public void onStart()

[Link]();

progressDialog =
[Link](this,"Please Wait",
"Processing...",true);
CountDownTimer timer = new
CountDownTimer(3000,1000) { @Override
public void onTick(long millisUntilFinished) {
}

@Override

public void onFinish() {


[Link]
s();
}

}.start();

}
3. Press Shift+F9 to debug the application on the Android emulator. You see
the progress dialog, as shown in Figure 3-7. It disappears after three
seconds.

How It Works
To create a progress dialog, you create an instance of the ProgressDialog class and call its
show()

method:
progressDialog = [Link](this,"Please Wait", "Processing...",true);

This displays the progress dialog shown in Figure 3-7. Because this is a modal
dialog, it will block the UI until it is dismissed. To close the dialog, you create a
timer that calls the dismiss() method after three seconds. (Chapter 12 covers
threads and calling methods that can do extraneous work from a thread while a
progress dialog is displayed.)
CountDownTimer timer = new CountDownTimer(3000,1000) {
@Override
public void onTick(long millisUntilFinished) {
}

@Override
public void onFinish() {
[Link]();
}
}.start();
After the three seconds have elapsed, you dismiss the dialog by calling the dismiss()

method.

FIGURE 3-7

The next section explains using Intents, which help you navigate between multiple
Activit
Linking Activities Using Intents

An intent is a description of an operation to be performed. An Intent is an object used to


request an action from another app component via the Android system.

What can intents do?

1. Start activities

 A button click starts a new activity for text entry


 Clicking Share opens an app that allows you to post a photo

2. Start services

 Initiate downloading a file in the background

3. Deliver broadcasts

 The system informs everybody that the phone is now charging

Explicit and implicit intents

1. Explicit Intent

 Starts a specific activity


 Request tea with milk delivered by Nikita
 Main activity starts the ViewShoppingCart activity

2. Implicit Intent

 Asks system to find an activity that can handle this request


 Find an open store that sells green tea
 Clicking Share opens a chooser with a list of apps
Starting Activities

Start an Activity with an explicit intent:

 To start a specific activity, use an explicit intent


 Create an intent

Intent intent = new Intent(this, [Link]);

 Use the intent to start the activity

startActivity(intent);

Start an Activity with implicit intent:

 To ask Android to find an Activity to handle your request, use an implicit intent
 Create an intent

Intent intent = new Intent(action, uri);

 Use the intent to start the activity


startActivity(intent);

How Activities Run

All activities are managed by the Android [Link] by an "intent", a


message to the Android runtime to run an activity

TRY IT OUT Linking Activities with Intents ([Link])


1. Using Android Studio, create a new Android project with an empty Activity named MainActivity;
name the project UsingIntent.
2. Right-click your package name under the app>>app>>src>>main>>java folder in the Project Files
windows and select New ➪ Java Class
3. Name the new class SecondActivity and click OK.
4. Add the bolded statements from the following code to the [Link] file. Be sure
to change all instances of "[Link]" to whatever package name your project is using.
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="[Link]
package="[Link]">

<application

android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

<activity android:name=".SecondActivity" >

<intent-filter >

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

5. Make a copy of the activity_main.xml file (in the res/layout folder) by right-clicking it
and selecting Copy. Then right-click the res/layout folder and select Paste. Name the file
activity_second.xml.
6. Modify the activity_second.xml file as follows:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link]
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="[Link]">

<TextView

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is the Second Activity!" />

</RelativeLayout>

7. In the [Link] file, add the bolded statements from the following code:
package [Link];

import [Link];
import [Link];

public class SecondActivity extends Activity {

public void onCreate(Bundle savedInstanceState) {


[Link](savedInstanceState);
setContentView([Link].activity_second);

}}

8. Add the bolded lines in the following code to the activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link]
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="[Link]">

<TextView

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Main Activity!"
android:id="@+id/textView" />

<Button

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display second activity"
android:onClick="onClick"
android:id="@+id/button"
android:layout_below="@+id/textView"
android:layout_alignParentStart="true"
android:layout_marginTop="56dp" />

</RelativeLayout>
9. Modify the [Link] file as shown in the bolded lines in the following code:
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends Activity

{ @Override

protected void onCreate(Bundle savedInstanceState) {


[Link](savedInstanceState);
setContentView([Link].activity_main);

public void onClick(View view) {

startActivity(new Intent("[Link]"));

10. Press Shift+F9 to debug the application on the Android emulator. When the first activity is loaded,
click the button and the second activity also loads (see Figures 3-8 and 3-9).

How It Works
As previously described, an activity is made up of a UI component (for example, activity_main.xml)
and a class component (for example, [Link]). If you want to add another activity to a
project, you need to create these two components.
Specifically, you need to add the following to the [Link] file:
</activity>

<activity android:name=".SecondActivity" >

<intent-filter >

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

When you add a new activity to the application, be sure to note the following:
➤ The name (class) of the new activity is SecondActivity.
➤ The intent filter name for the new activity is <Your Package Name>.SecondActivity. Other
activities that want to call this activity invoke it via this name. Ideally, you should use the
reverse domain name of your company as the intent filter name to reduce the chances of another
application having the same intent filter name.
➤ The category for the intent filter is [Link]. You need to add this to
the intent filter so that this activity can be started by another activity using the startActivity()
method (more on this shortly).

FIGURE 3-8 FIGURE 3-9

When the Display Second Activity button is clicked, you use the startActivity() method to display
SecondActivity by creating an instance of the Intent class and passing it the intent filter name of
SecondActivity ([Link]):

public void onClick(View view) {

startActivity(new Intent("[Link]"));

Activities in Android can be invoked by any application running on the device. For example, you can
create a new Android project and then display SecondActivity by using its net.learn2develop
.SecondActivity intent filter. This is one of the fundamental concepts in Android that enables an
application to easily invoke another application.
If the activity you want to invoke is defined within the same project, you can rewrite the
preceding statement like this:
startActivity(new Intent(this, [Link]));
Fragment:

Fragment is a piece of an activity which enables more modular activity design. It will not
be wrong if we say, a fragment is a kind of sub-activity.

Following are important points about fragment −

 A fragment has its own layout and its own behaviour with its own life cycle callbacks.
 You can add or remove fragments in an activity while the activity is running.
 You can combine multiple fragments in a single activity to build a multi-pane UI.
 A fragment can be used in multiple activities.
 Fragment life cycle is closely related to the life cycle of its host activity which means
when the activity is paused, all the fragments available in the activity will also be
stopped.
 A fragment can implement a behaviour that has no user interface component.
 Fragments were added to the Android API in Honeycomb version of Android API version
11.

You create fragments by extending Fragment class and You can insert a fragment into your
activity layout by declaring the fragment in the activity's layout file, as a element.

The application can embed two fragments in Activity A, when running on a tablet-sized device.
However, on a handset-sized screen, there's not enough room for both fragments, so Activity A
includes only the fragment for the list of articles, and when the user selects an article, it starts
Activity B, which includes the second fragment to read the article.

Fragment Lifecycle

Android fragments have their own life cycle very similar to an android activity. This section briefs
different stages of its life cycle.
Here is the list of methods which you can to override in your fragment class −

 onAttach( ) The fragment instance is associated with an activity [Link] fragment


and the activity is not fully initialized. Typically you get in this method a reference to the
activity which uses the fragment for further initialization work.
 onCreate( ) The system calls this method when creating the fragment. You should
initialize essential components of the fragment that you want to retain when the
fragment is paused or stopped, then resumed.
 onCreateView( ) The system calls this callback when it's time for the fragment to draw
its user interface for the first time. To draw a UI for your fragment, you must return a
View component from this method that is the root of your fragment's layout. You can
return null if the fragment does not provide a UI.
 onActivityCreated( ) The onActivityCreated() is called after the onCreateView() method
when the host activity is created. Activity and fragment instance have been created as
well as the view hierarchy of the activity. At this point, view can be accessed with the
findViewById() method. example. In this method you can instantiate objects which
require a Context object
 onStart( ) method is called once the fragment gets visible.
 onResume( ) Fragment becomes active.
 onPause( ) The system calls this method as the first indication that the user is leaving
the fragment. This is usually where you should commit any changes that should be
persisted beyond the current user session.
 onStop( ) Fragment going to be stopped by calling onStop()
 onDestroyView( ) Fragment view will destroy after call this method
 onDestroy( ) called to do final clean up of the fragment's state but Not guaranteed to
be called by the Android platform.

Types of Fragments

Basically fragments are divided as three stages as shown below.

 Single frame fragments − Single frame fragments are used for handheld devices like
mobiles, here we can show only one fragment as a view.
 List fragments − fragments having special list view is called as list fragment
 Fragment transaction − Using a fragment transaction. we can move one fragment to
another fragment

TRY IT OUT Using Fragments ([Link])


1. Using Android Studio, create a new Android project and name it Fragments.
2. In the res/layout folder, add a new layout resource file and name it [Link]. Populate
it with the following code. Be sure to change all instances of "[Link]" to whatever
package name your project is using.
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout

xmlns:android="[Link]
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#00FF00"

>

<TextView

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is fragment #1"
android:textColor="#000000"
android:textSize="25sp" />

</LinearLayout>

3. Also in the res/layout folder, add another new layout resource file and name it [Link].
Populate it as follows:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout

xmlns:android="[Link]
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFE00"

>

<TextView

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is fragment #2"
android:textColor="#000000"
android:textSize="25sp" />

</LinearLayout>
4. In activity_main.xml, add the bolded lines in the following code:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout android:orientation="vertical"
xmlns:android="[Link]
xmlns:tools="[Link]
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="[Link]">

<fragment
android:name="[Link].Fragment1"
android:id="@+id/fragment1"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="match_parent" />

<fragment

android:name="[Link].Fragment2"
android:id="@+id/fragment2"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="match_parent" />

</LinearLayout>

5. Under the <Your Package Name>/fragments package name, add two Java class files and name
them [Link] and [Link].
6. Add the following code to [Link]:
package [Link];

import [Link];
import [Link];

import [Link];
import [Link];

import [Link];

public class Fragment1 extends Fragment


{ @Override

public View onCreateView(LayoutInflater inflater,

ViewGroup container, Bundle savedInstanceState) {

//---Inflate the layout for this


fragment--- return [Link](

[Link].fragment1, container, false);

}
7. Add the following code to [Link]:
package [Link];

import [Link];
import [Link];

import [Link];
import [Link];

import [Link];

public class Fragment2 extends Fragment


{ @Override

public View onCreateView(LayoutInflater inflater,

ViewGroup container, Bundle savedInstanceState) {

//---Inflate the layout for this


fragment--- return [Link](

[Link].fragment2, container, false);

8. Press Shift+F9 to debug the application on the Android emulator. Figure 3-16 shows the two
fragments contained within the activity.
Adding Fragments Dynamically
Although fragments enable you to compartmentalize your UI into various
configurable parts, the real power of fragments is realized when you add them
dynamically to activities during runtime. In the previous section, you saw how you
can add fragments to an activity by modifying the XML file during design time. In
reality, it is much more useful if you create fragments and add them to activi- ties
during runtime. This enables you to create a customizable user interface for your
application.
For example, if the application is running on a smartphone, you might
fill an activity with a single fragment; if the application is running on a tablet,
you might then fill the activity with two or more fragments, as the tablet has
much more screen real estate compared to a smartphone.

Interactions Between Fragments


Very often, an activity might contain one or more fragments working together to
present a coherent UI to the user. In this case, it is important for fragments to
communicate with one another and exchange data. For example, one fragment
might contain a list of items (such as postings from an RSS feed).
Also, when the user taps on an item in that fragment, details about the selected
item might be dis- played in another fragment

Displaying Notifications

A notification is a message you can display to the user outside of your


application's normal UI. When you tell the system to issue a notification, it first appears
as an icon in the notification area. To see the details of the notification, the user opens
the notification drawer. Both the notification area and the notification drawer are system-
controlled areas that the user can view at any time.

To see the details of the notification, you will have to select the icon which will display the
notification drawer having detail about the notification. While working with an emulator
with a virtual device, you will have to click and drag down the status bar to expand it
which will give you detail as follows. This will be just 64 dp tall and called normal view.
Create and Send Notifications

You have a simple way to create a notification. Follow the following steps in your application to
create a notification −

Step 1 - Create Notification Builder

As a first step is to create a notification builder using [Link](). You will


use Notification Builder to set various Notification properties like its small and large icons, title,
priority etc.

[Link] mBuilder = new [Link](this)

1
[Link] mBuilder = new [Link](this)
Step 2 - Setting Notification Properties

Once you have a Builder object, you can set its Notification properties using Builder object as per
your requirement. But this is mandatory to set at least following −

 A small icon, set by setSmallIcon()

 A title, set by setContentTitle()

 Detail text, set by setContentText()

[Link]([Link].notification_icon);
[Link]("Notification Alert, Click Me!");

[Link]("Hi, This is Android Notification Detail!");

1
[Link]([Link].notification_icon);
2
[Link]("Notification Alert, Click Me!");
3
[Link]("Hi, This is Android Notification Detail!");

You have plenty of optional properties which you can set for your notification. To learn more
about them, see the reference documentation for [Link].

Step 3 - Attach Actions

This is an optional part and required if you want to attach an action with the notification. An
action allows users to go directly from the notification to an Activity in your application, where
they can look at one or more events or do further work.

The action is defined by a PendingIntent containing an Intent that starts an Activity in your
application. To associate the PendingIntent with a gesture, call the appropriate method of
[Link]. For example, if you want to start Activity when the user clicks the
notification text in the notification drawer, you add the PendingIntent by calling
setContentIntent().

A PendingIntent object helps you to perform an action on your applications behalf, often at a
later time, without caring of whether or not your application is running.

We take help of stack builder objects which will contain an artificial back stack for the started
Activity. This ensures that navigating backward from the Activity leads out of your application to
the Home screen.

ntent resultIntent = new Intent(this, [Link]);


TaskStackBuilder stackBuilder = [Link](this);
[Link]([Link]);
// Adds the Intent that starts the Activity to the top of the stack
[Link](resultIntent);
PendingIntent resultPendingIntent =
[Link](0,PendingIntent.FLAG_UPDATE_CURRENT);
[Link](resultPendingIntent);

1
Intent resultIntent = new Intent(this, [Link]);
2
TaskStackBuilder stackBuilder = [Link](this);
3
[Link]([Link]);
4
// Adds the Intent that starts the Activity to the top of the stack
5
[Link](resultIntent);
6
PendingIntent resultPendingIntent =
[Link](0,PendingIntent.FLAG_UPDATE_CURRENT);
7
[Link](resultPendingIntent);
Step 4 - Issue the notification

Finally, you pass the Notification object to the system by calling [Link]() to
send your notification. Make sure you call [Link]() method on builder
object before notifying it. This method combines all of the options that have been set and return
a new Notification object.

NotificationManage mNotificationManager = (NotificationManager)


getSystemService(Context.NOTIFICATION_SERVICE);
// notificationID allows you to update the notification later on.
[Link](notificationID, [Link]());

TRY IT OUT Displaying Notifications on the Status Bar ([Link])


1. Using Android Studio, create a new Android project and name it Notifications.
2. Add a new class file named NotificationView to the package. In addition, add a new
[Link] layout resource file to the res/layout folder.

3. Populate the [Link] file as follows. Be sure to change all instances of


"[Link]" to whatever package name your project is using)

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

<LinearLayout xmlns:android="[Link]
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView

android:layout_width="fill_parent"
android:layout_height="wrap_content"

android:text="Here are the details for the notification..." />

</LinearLayout>

4. Populate the [Link] file as follows:


package [Link];

import [Link];

import [Link];
import [Link];
public class NotificationView extends Activity

{ @Override

public void onCreate(Bundle savedInstanceState)


{

[Link](savedInstanceState);
setContentView([Link]);

//---look up the notification manager


service--- NotificationManager nm =
(NotificationManager)

getSystemService(NOTIFICATION_SERVICE);

//---cancel the notification that we started---


[Link](getIntent().getExtras().getInt("notificationID"));

5. Add the following statements in bold to the [Link] file:


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

<manifest xmlns:android="[Link]
package="[Link]">

<uses-permission android:name="[Link]"/>

<application

android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

<activity android:name=".NotificationView"
android:label="Details of notification">

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />


</intent-filter>

</activity>

</application>

</manifest>

6. Add the following statements in bold to the activity_main.xml file:


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

<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link]
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="[Link]">

<Button

android:id="@+id/btn_displaynotif"

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Display Notification"
android:onClick="onClick"/>

</RelativeLayout>

7. Add the following statements in bold to the [Link] file:


package [Link];

import [Link];

import [Link];
import [Link];
import [Link];

import [Link];

import [Link];
import [Link];

public class MainActivity extends Activity {

int notificationID = 1;

@Override

protected void onCreate(Bundle savedInstanceState) {


[Link](savedInstanceState);
setContentView([Link].activity_main);

}
public void onClick(View view) {
displayNotification();

protected void displayNotification()

//---PendingIntent to launch activity if the user selects

// this notification---

Intent i = new Intent(this, [Link]);


[Link]("notificationID", notificationID);

PendingIntent pendingIntent = [Link](this, 0, i, 0);

NotificationManager nm = (NotificationManager)getSystemService
(NOTIFICATION_SERVICE);

[Link] notifBuilder;
notifBuilder = new [Link](this)

.setSmallIcon([Link].ic_launcher)

.setContentTitle("Meeting Reminder")

.setContentText("Reminder: Meeting starts in 5 minutes");


[Link](notificationID, [Link]());

8. Press Shift+F9 to debug the application on the Android emulator.


9. Click the Display Notification button and a notification ticker text (set in the constructor of the
Notification object) displays on the status bar.

10. Click and drag the status bar down to reveal the notification details set using the
setLatestEventInfo() method of the Notification object (see Figure 3-19).

Understanding the Components of a Screen


Application components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file [Link] that
describes each component of the application and how they interact.

There are following four main components that can be used within an Android application −

Activities

An activity represents a single screen with a user interface,in-short Activity performs


actions on the screen. For example, an email application might have one activity that shows a
list of new emails, another activity to compose an email, and another activity for reading emails.
If an application has more than one activity, then one of them should be marked as the activity
that is presented when the application is launched.

An activity is implemented as a subclass of Activity class as follows –

public class MainActivity extends Activity {


}
1
public class MainActivity extends Activity {
2
}
Services

A service is a component that runs in the background to perform long-running operations.


For example, a service might play music in the background while the user is in a different
application, or it might fetch data over the network without blocking user interaction with an
activity.

A service is implemented as a subclass of Service class as follows –


public class MyService extends Service {
}

1
public class MyService extends Service {
2
}

Broadcast Receivers

Broadcast Receivers simply respond to broadcast messages from other applications or


from the system. For example, applications can also initiate broadcasts to let other applications
know that some data has been downloaded to the device and is available for them to use, so this
is a broadcast receiver who will intercept this communication and will initiate appropriate action.

A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each


message is broadcast as an Intent object.

public class MyReceiver extends BroadcastReceiver {


public void onReceive(context,intent){}
}
1
public class MyReceiver extends BroadcastReceiver {
2
public void onReceive(context,intent){}
3
}
Content Providers

A content provider component supplies data from one application to others on request.
Such requests are handled by the methods of the ContentResolver class. The data may be
stored in the file system, the database or somewhere else entirely.

A content provider is implemented as a subclass of ContentProvider class and must implement a


standard set of APIs that enable other applications to perform transactions.

public class MyContentProvider extends ContentProvider {


public void onCreate(){}
}
1
public class MyContentProvider extends ContentProvider {
2
public void onCreate(){}
3
}
Additional Components
There are additional components which will be used in the construction of above
mentioned entities, their logic, and wiring between them. These components are −
Views and ViewGroups

• Views

– An activity contains views and ViewGroups.

– A view is a widget that has an appearance on screen.

– Examples of views are buttons, labels, and textboxes.

– A view derives from the base class [Link].

• View Groups

– One or more views can be grouped together into a ViewGroup.

– A ViewGroup provides the layout in which you can order the appearance and
sequence of views.

– Examples of ViewGroups include LinearLayout and FrameLayout.

A ViewGroup derives from the base class [Link]

– Linear Layout

– Absolute Layout

– Table Layout

– Relative Layout

– Frame Layout

– Scroll View

Views and View Groups-Linear Layout

• Linear Layout

– Android Linear Layout is a view group that aligns all children in


either vertically or horizontally.

– The Linear Layout arranges views in a single column or a single row.

– Child views can be arranged either vertically or horizontally.


android:id This is the ID which uniquely identifies the layout

android:baselineAligned This must be a boolean value, either "true" or "false" and


prevents the layout from aligning its children's baseline
android:divider This is drawable to use as a vertical divider between
buttons. You use a color value, in the form of "#rgb",
"#argb", "#rrggbb", or "#aarrggbb".
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:orientation This specifies the direction of arrangement and you will use
"horizontal" for a row, "vertical" for a column. The default is
horizontal.

Try Out:

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

<LinearLayout xmlns:android=”[Link]

android:layout_width=”fill_parent”

android:layout_height=”fill_parent”

android:orientation=”vertical” >

<TextView

android:layout_width=”100dp”

android:layout_height=”wrap_content”

android:text=”@string/hello” />

<Button

android:layout_width=”160dp”

android:layout_height=”wrap_content”

android:text=”Button”

android:onClick=”onClick” />

</LinearLayout>
Views and View Groups –Absolute Layout

• Absolute Layout

– The Absolute Layout enables you to specify the exact location of its children.

– there is a problem with the Absolute Layout when the activity is viewed on a high
resolution views will be improperly placed

– For this reason, the Absolute Layout has been deprecated since Android 1.5

TRY OUT AbsoluteLayout:

android:layout_width=”fill_parent” android:layout_x=”126px”

android:layout_height=”fill_parent” android:layout_y=”361px” />

xmlns:android=”http:// <Button
[Link]/apk/res/android” >
android:layout_width=”113dp”
<Button
android:layout_height=”wrap_content”
android:layout_width=”188dp”
android:text=”Button”
android:layout_height=”wrap_content”
android:layout_x=”12px”
android:text=”Button”
android:layout_y=”361px” />
</AbsoluteLayout>

Views and ViewGroups – TableLayout


• Table Layout
 The TableLayout groups views into rows and columns.
 we use the <TableRow> element to designate a row in the table.
 Each row can contain one or more views.
 Each view can be placed within a row forms a cell.
 The width of each column is determined by the largest width of each cell in
that column

Try Out TableLayout


xmlns:android=”http:// />
[Link]/apk/res/android”
<EditText
android:layout_height=”fill_parent”
android:id=”@+id/txtUserName”
android:layout_width=”fill_parent” >
android:width=”200dp” />
<TableRow>
</TableRow>
<TextView
<TableRow>
android:text=”User Name:”
<TextView
android:width =”120dp”
android:text=”Password:”
/> android:layout_width=”fill_parent”
<EditText android:layout_height=”wrap_content”
android:id=”@+id/txtPassword” android:text=”Remember Password”
android:password=”true” />
/> </TableRow>
</TableRow> <TableRow>
<TableRow> <Button
<TextView /> android:id=”@+id/buttonSignIn”
<CheckBox android:text=”Log In” />
android:id=”@+id/chkRememberPasswo
</TableRow>
rd”
</TableLayout>
Views and View Groups –Relative Layout
• Relative Layout
– The Relative Layout enables you to specify how child views are positioned
relative to each other.
– The position of each view can be specified as relative to sibling elements
or relative to the parent.
– you can align two elements by right border, or make one below another,
centered in the screen, centered left, and so on.
– By default, all child views are drawn at the top-left of the layout
Try Out:
<?xml version=”1.0” encoding=”utf-8”? android:layout_alignParentLeft=”true” /
> >
<RelativeLayout <EditText
android:id=”@+id/RLayout” android:id=”@+id/txtComments”
android:layout_width=”fill_parent”
android:layout_width=”fill_parent”
android:layout_height=”170px”
android:layout_height=”fill_parent”
android:textSize=”18sp”
xmlns:android=”http://
[Link]/apk/res/android” android:layout_alignLeft=”@+id/
> lblComments”
<TextView android:layout_below=”@+id/
lblComments”
android:id=”@+id/lblComments”
android:layout_centerHorizontal=”true”
android:layout_width=”wrap_content”
/>
android:layout_height=”wrap_content”
<Button
android:text=”Comments”
android:id=”@+id/btnSave”
android:layout_alignParentTop=”true”
android:layout_width=”125px”
android:layout_height=”wrap_content” android:id=”@+id/btnCancel”
android:text=”Save” android:layout_width=”124px”
android:layout_below=”@+id/ android:layout_height=”wrap_content”
txtComments”
android:text=”Cancel”
android:layout_alignRight=”@+id/
android:layout_below=”@+id/
txtComments” />
txtComments”
<Button
android:layout_
 That each view embedded within the Relative Layout has attributes that enable it
to align with another view.
 These attributes are as follows:
➤ layout_alignParentTop ➤ layout_centerHorizontal
➤ layout_alignParentLeft ➤ android:layout_toEndOf
➤ layout_alignLeft ➤ android:layout_toRightOf
➤ layout_alignRight ➤ android:layout_toLeftOf
➤ layout_below ➤ android:layout_toStartOf

1
NotificationManage mNotificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
2
// notificationID allows you to update the notification later on.
3
[Link](notificationID, [Link]());
Frame Layout
 The Frame Layout is a placeholder on screen that you can use to display a
single view.
 Views that you add to a Frame Layout are always anchored to the top left
of the layout.
 If you add another view (within the Frame Layout), the view will overlap
the previous view

<?xml version=”1.0” encoding=”utf- android:layout_height=”wrap_conten


8”?> t”

<RelativeLayout android:text=”Hello, Android!”

android:id=”@+id/RLayout” android:layout_alignParentTop=”true

android:layout_width=”fill_parent”
android:layout_alignParentLeft=”true
android:layout_height=”fill_parent” ” />
xmlns:android=”http:// <FrameLayout
[Link]/apk/res/android” >
android:layout_width=”wrap_content
<TextView ”
android:id=”@+id/lblComments” android:layout_height=”wrap_conten
android:layout_width=”wrap_content t”

android:layout_alignLeft=”@+id/ android:src = “@drawable/droid”
lblComments”
android:layout_width=”wrap_content
android:layout_below=”@+id/ ”
lblComments”
android:layout_height=”wrap_conten
android:layout_centerHorizontal=”tru t” />
e” >
</FrameLayout>
<ImageView
</RelativeLayout>

Scroll View

 A Scroll View is a special type of Frame Layout in that it enables users to scroll through a list
of views that occupy more space than the physical display.

 The Scroll View can contain only one child view or ViewGroup, which normally is a
LinearLayout.

ScrollView xmlns:android=”http://
[Link]/apk/res/
android:layout_width=”fill_parent
android” >

<LinearLayout
android:layout_height=”fill_paren
t” android:layout_width=”fill_parent

android:layout_height=”wrap_con android:text=”Button 3” />
tent”
<EditText
android:orientation=”vertical” >
android:id=”@+id/txt”
<Button
android:layout_width=”fill_parent
android:id=”@+id/button1” ”

android:layout_width=”fill_parent android:layout_height=”600dp” /
” >

android:layout_height=”wrap_con <Button
tent”
android:id=”@+id/button4”
android:text=”Button 1” />
android:layout_width=”fill_parent
<Button ”

android:id=”@+id/button2” android:layout_height=”wrap_con
tent”
android:layout_width=”fill_parent
” android:text=”Button 4” />

android:layout_height=”wrap_con <Button
tent”
android:id=”@+id/button5”
android:text=”Button 2” />
android:layout_width=”fill_parent
<Button ”

android:id=”@+id/button3” android:layout_height=”wrap_con
tent”
android:layout_width=”fill_parent
” android:text=”Button 5” />

android:layout_height=”wrap_con </LinearLayout>
tent”
</ScrollView

To prevent it from getting the focus, add the following two attributes to the
<LinearLayout> element:
<LinearLayout android:layout_width=”fill_parent”
android:layout_height=”wrap_content” android:orientation=”vertical”
android:focusable=”true” android:focusableInTouchMode=”true” >
Adapting to Display Orientation

 One of the key features of modern smartphones is their ability to switch screen 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 will automatically redraw its content in the new orientation.

 This is because the onCreate() event of the activity is fired whenever there is a change in
display orientation.

 When you change the orientation of your Android device, your current activity is actually
destroyed and then re-created.

 As you can observe in landscape mode, a lot of empty space on the right of the screen could
be used.

 Furthermore, any additional views at the bottom of the screen would be hidden when the
screen orientation is set to landscape.
Handling changes in screen 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 nearly 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 could be easily achieved by using RelativeLayout

Consider the following [Link] containing five Button views embedded within the
<RelativeLayout> element:

Anchoring Views – Example


<?xml version="1.0" encoding="utf-8"?> android:layout_alignParentRight="true"
<Relative Layout <Button
android:layout_width="fill_parent" android:id="@+id/button3"
android:layout_height="fill_parent" android:layout_width="wrap_content"
xmlns:android="[Link] android:layout_height="wrap_content"
android com/apk/res/android android:text= Bottom Left Button"
<Button android:layout_alignParentLeft="true"
android:id="@+id/button1" android:layout_alignParentBottom="true"<B
android:layout_width="wrap_content" utton
android:layout_height="wrap_content" android:id="@+id/button4"
android:text= Top Left Button" android:layout_width="wrap_content"
android:layout_alignParentLeft="true" android:layout_height="wrap_content"
android:layout_alignParent Top="true" android:text="Bottom Right Button"
<Button android:layout_alignParentRight="true"
android:id="@+id/button2" android:layout_alignParentBottom="true”
android:layout_width="wrap_content" <Button
android:layout_height="wrap_content" android:id="@+id/button5
android:text="Top Right Button" android:layout_width="fill parent"
android:layout_alignParentTop="true" android:layout_height="wrap_content"
android:text= Middle Button" android:layout_center Horizontal="true"
android:layout_center Vertical="true" </RelativeLayout>

1
<?xml version="1.0" encoding="utf-8"?>
2
<Relative Layout
3
android:layout_width="fill_parent"
4
android:layout_height="fill_parent"
5
xmlns:android="[Link] android com/apk/res/android
6
<Button
7
android:id="@+id/button1"
8
android:layout_width="wrap_content"
9
android:layout_height="wrap_content"
10
android:text= Top Left Button"
11
android:layout_alignParentLeft="true"
12
android:layout_alignParent Top="true"
13
<Button
14
android:id="@+id/button2"
15
android:layout_width="wrap_content"
16
android:layout_height="wrap_content"
17
android:text="Top Right Button"
18
android:layout_alignParentTop="true"
19
android:layout_alignParentRight="true"
20
<Button
21
android:id="@+id/button3"
22
android:layout_width="wrap_content"
23
android:layout_height="wrap_content"
24
android:text= Bottom Left Button"
25
android:layout_alignParentLeft="true"
26
android:layout_alignParentBottom="true"
27
<Button
28
android:id="@+id/button4"
29
android:layout_width="wrap_content"
30
android:layout_height="wrap_content"
31
android:text="Bottom Right Button"
32
android:layout_alignParentRight="true"
33
android:layout_alignParentBottom="true”
34
<Button
35
android:id="@+id/button5
36
android:layout_width="fill parent"
37
android:layout_height="wrap_content"
38
android:text= Middle Button"
39
android:layout_center Vertical="true"
40
android:layout_center Horizontal="true"
41
</RelativeLayout>
 When the screen orientation changes to landscape mode

 the four buttons are aligned to the four edges of the screen, and the center button is centered
in the middle of the screen with its width fully stretched

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 Ul 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).

Managing Changes to Screen Orientation

When configurations change during run time (such as screen orientation, keyboard availability,
and language), Android usually destroys an application's existing Activity or Fragment and
recreates it.

Android does this so that applications can reload its resources based on the new configuration.
The restart behavior helps applications to adapt new configurations by automatically reloading
the application with alternative resources that match the new device configuration.

Proper handling of orientation changes makes rich user experience (not lost UI state) for the
application and it also avoids memory leaks.

How to handle it?


To handle these configuration changes, Android provides callbacks to save your application state
before destroying either Activity or Fragment. In the same it also provides to restore the
application state when it is recreating them.

There are a different options to handle the orientation changes:

 Lock screen orientation

 Prevent Activity to recreated

 Save basic state

 Save complex objects

Lock screen orientation


To lock the screen orientation change of any screen (activity) of your android application
makes your activity display only in one mode i.e. either Landscape or Portrait. This is the
simplest way to handle screen orientation but not generally recommended.

For this you need to add the below line in your projects [Link]. Add the below line
along with your activity entry in the AndroidManifest file.

Prevent Activity to recreated

Another most common solution to dealing with orientation changes by setting the
android:configChanges flag on your Activity in [Link]. Using this attribute your
Activities won’t be recreated and all your views and data will still be there after orientation
change.

This attribute informs the Android system that you are going to handle orientation and
screenSize changes for this Activity. So instead of destroying and recreating your Activity,
Android will just rotate the screen and invoke one of the lifecycle callback methods which is
onConfigurationChanged(Configuration).

Save basic state

This is the most common situation to save the basic data of your Activity or Fragment
during orientation change. You can save Primitive data such as String, Boolean, Integers or
Parcelable objects in a Bundle during the orientation change and read the same data when
Activity recreated.

Saving and restoring the data works using two Activity lifecycle methods called
onSaveInstanceState() and onRestoreInstanceState().
To save the state information override onSaveInstanceState() method and add key-value pairs to
the Bundle object that is saved in the event that your activity is destroyed unexpectedly. This
method gets called before onStop().

To recover your saved state from the Bundle override onRestoreInstanceState() method. This is
called after onStart() and before onResume().

Save complex objects

Override onRetainNonConfigurationInstance() and


getLastNonConfigurationInstance() Prior to Honeycomb’s release, the recommended means
of transferring active objects across Activity instances was to override the
onRetainNonConfigurationInstance() and getLastNonConfigurationInstance() methods. After API
level 13 these methods have been deprecated in favor of the more Fragment’s
setRetainInstance(boolean) capability, which provides a much cleaner and modular means of
retaining objects during configuration changes.

Utilizing the Action Bar

Action Bar is one of the important parts of any application, whether it’s a web application
or a mobile app. Today we will learn how to implement an action bar in android apps using the
ActionBar component.

Android ActionBar is a menu bar that runs across the top of the activity screen in android.
Android ActionBar can contain menu items which become visible when the user clicks the
“menu” button.

In general an ActionBar consists of the following four components:

 App Icon: App branding logo or icon will be displayed here

 View Control: A dedicated space to display Application title. Also provides option to switch
between views by adding spinner or tabbed navigation

 Action Buttons: Some important actions of the app can be added here

 Action Overflow: All unimportant action will be shown as a menu

Android ActionBar Setting Up


All activities that use the theme [Link] or a theme derived from [Link] will
automatically contain an ActionBar.

Android ActionBar Menu


The simplest way to get toolbar icons and action overflow items into the action bar is by creating
the menu XML resource file found in res/menu folder. Add menu items in the raw xml file present
in the folder as follows:

<menu xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link] tools:context=".MainActivity">
<item
android:id="@+id/add" android:icon="@android:drawable/ic_menu_add"
app:showAsAction="always" android:title="@string/add"/>
<item
android:id="@+id/reset" android:icon="@android:drawable/ic_menu_revert"
app:showAsAction="always|withText" android:title="@string/reset"/>
<item
android:id="@+id/about" android:icon="@android:drawable/ic_dialog_info"
app:showAsAction="never" android:title="@string/about">
</item>
<item
android:id="@+id/exit" app:showAsAction="never"
android:title="@string/exit">
</item>
</menu>

There are four things that are needed to be configured for every menu item.

 android:id: attribute specifies the id of the menu item. This works like ids anywhere else in
the Android app. An android:id value starting with a @+id/ will create a constant in the [Link]
constant collection
 android:title: attribute value contains the title of the menu item
 android:icon: attribute references an icon in the drawable directories
 android:showAsAction: This attribute indicates how the given item should be portrayed in
the action bar.

CREATING THE USER INTERFACE PROGRAMMATICALLY


This approach is useful if your UI needs to be dynamically generated during runtime. For example,
suppose you are building a cinema ticket reservation system and your application displays the seats of each
cinema using buttons. In this case, you need to dynamically generate the UI based on the cinema
selected by the user.

TRY IT OUT Creating the UI via Code ([Link])


 Using Android Studio, create a new Android project and name it UICode.
 In the [Link] file, add the bold statements in the following code:
import [Link]; import
[Link];
import [Link];
import [Link];

import [Link]; import


[Link];

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {


[Link](savedInstanceState);
[Link] params =

new [Link](
[Link].WRAP_CONT
ENT,
[Link].WRAP_CONT
ENT);

//---create a layout---

LinearLayout layout = new LinearLayout(this);


[Link]([Link]);

//---create a textview--- TextView


tv = new TextView(this);
[Link]("This is a TextView");
[Link](params);

//---create a button---

Button btn = new Button(this);


[Link]("This is a Button");
[Link](params);

//---adds the textview---


[Link](tv);

//---adds the button---


[Link](btn);

//---create a layout param for the layout---


[Link]
layoutParam =

new [Link](
[Link].WRAP_CONTE
NT,
[Link].WRAP_CONTE
NT );

[Link](layout, layoutParam);

 Press Shift+F9 to 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

You might also like