Android Activity Lifecycle Explained
Android Activity Lifecycle Explained
UNDERSTANDING ACTIVITIES
<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
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.
Implementing Activities
Define layout in XML
Define Activity Java class
extends AppCompatActivity
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
onStop( )—no longer visible, but still exists and all state info preserved
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
}
import
[Link];
import [Link];
import [Link];
[Link]();
[Link]();
}
}
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>
</intent-filter>
</activity>
</application>
</manifest>
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;
<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>
</activity>
</application>
</manifest>
FIGURE 3-5
<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]" />
</intent-filter>
</activity>
</application>
</manifest>
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_dialog);
Toolbar toolbar = (Toolbar) findViewById([Link]);
setSupportActionBar(toolbar);
});
@Override
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate([Link].menu_dialog, menu);
return true;
}
@Override
// Handle action bar item clicks here. The action bar will
//noinspection SimplifiableIfStatement
if (id == [Link].action_settings) {
return true;
}
return [Link](item);
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>
</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
[Link]();
progressDialog =
[Link](this,"Please Wait",
"Processing...",true);
CountDownTimer timer = new
CountDownTimer(3000,1000) { @Override
public void onTick(long millisUntilFinished) {
}
@Override
}.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
1. Start activities
2. Start services
3. Deliver broadcasts
1. Explicit Intent
2. Implicit Intent
startActivity(intent);
To ask Android to find an Activity to handle your request, use an implicit intent
Create an intent
<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>
</intent-filter>
</activity>
<intent-filter >
</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];
}}
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];
{ @Override
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>
<intent-filter >
</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).
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]):
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.
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 −
Types of Fragments
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
<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];
}
7. Add the following code to [Link]:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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.
Displaying Notifications
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 −
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 −
[Link]([Link].notification_icon);
[Link]("Notification Alert, Click Me!");
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].
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.
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.
<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"
</LinearLayout>
import [Link];
import [Link];
import [Link];
public class NotificationView extends Activity
{ @Override
[Link](savedInstanceState);
setContentView([Link]);
getSystemService(NOTIFICATION_SERVICE);
<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>
</intent-filter>
</activity>
<activity android:name=".NotificationView"
android:label="Details of notification">
<intent-filter>
</activity>
</application>
</manifest>
<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>
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
int notificationID = 1;
@Override
}
public void onClick(View view) {
displayNotification();
// this notification---
NotificationManager nm = (NotificationManager)getSystemService
(NOTIFICATION_SERVICE);
[Link] notifBuilder;
notifBuilder = new [Link](this)
.setSmallIcon([Link].ic_launcher)
.setContentTitle("Meeting Reminder")
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).
There are following four main components that can be used within an Android application −
Activities
1
public class MyService extends Service {
2
}
Broadcast Receivers
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.
• Views
• View Groups
– A ViewGroup provides the layout in which you can order the appearance and
sequence of views.
– Linear Layout
– Absolute Layout
– Table Layout
– Relative Layout
– Frame Layout
– Scroll View
• Linear Layout
Try Out:
<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
android:layout_width=”fill_parent” android:layout_x=”126px”
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>
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
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
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
Consider the following [Link] containing five Button views embedded within the
<RelativeLayout> element:
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
To support landscape mode, you can create a new folder in the res folder and name it as
layout-land (representing landscape).
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.
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.
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).
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().
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.
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
<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.
@Override
new [Link](
[Link].WRAP_CONT
ENT,
[Link].WRAP_CONT
ENT);
//---create a layout---
//---create a button---
new [Link](
[Link].WRAP_CONTE
NT,
[Link].WRAP_CONTE
NT );
[Link](layout, layoutParam);