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

Chapter 5 Android User Interface

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Chapter 5 Android User Interface

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

DDWD2713 – Mobile Programming 1

CHAPTER 5

ANDROID USER INTERFACE:

Course Outline Chapter 4


✓ Coding the application

✓ Activities

✓ Creating Activities

✓ Working with framework class

✓ Installing application

✓ Responding to error

Activity
• In android, Activity represents a single screen with a user interface (UI) of an
application and it will act an entry point for users to interact with an app.
• Generally, the android apps will contain multiple screens and each screen of our
application will be an extension of Activity class. By using activities, we can place all our
android application UI components in a single screen.
• From the multiple activities in android app, one activity can be marked as a main
activity and that is the first screen to appear when we launch the application.
• In android app each activity can start another activity to perform different actions based
on our requirements.
• Generally, in android there is a minimal dependency between the activities in an app. To
use activities in application we need to register those activities information in our app’s
manifest file (AndroidMainfest.xml) and need to manage activity life cycle properly.
• To use activities in our application we need to define an activity with required attributes
in manifest file (AndroidMainfest.xml) like as shown below
DDWD2713 – Mobile Programming 2

Android Activity Lifecycle


• Generally, the activities in our android application will go through a different stage in
their life cycle.
• In android, Activity class have 7 callback methods like
i. onCreate()
ii. onStart()
iii. onPause()
iv. onRestart()
v. onResume()
vi. onStop()
vii. onDestroy()

• By using activity callback methods, we can define how our activity can behave when the
user enters or leaves our application.

Android Activity Lifecycle Callback Methods


• In android, an activity goes through a series of states during its lifetime.
• By using callback methods, we can get the activity transitions between the states.
• Android system initiates its program within an Activity starting with a call
on onCreate() callback method. There is a sequence of callback methods that start up an
activity and a sequence of callback methods that tear down an activity.
• This section will give you detailed information about callback methods to handle activity
transitions between states during the lifecycle.

1. onCreate()
• First callback method, and it fires when the system creates an activity for the first time.
• If we have an application start-up logic that needs to perform only once during the life
cycle of an activity, then we can write that logic in onCreate() method.
• Following is the example of defining a onCreate() method in android activity.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
DDWD2713 – Mobile Programming 3

2. onStart()
• The onStart() callback method will invoke after onCreate() method completed.
• Following is the example of defining a onStart() method in android activity.

@Override
protected void onStart()
{
super.onStart()
}

3. onResume()
• After completion of onStart() method execution, the activity enters into Resumed
state and system invoke the onResume() method.
• In case if any interruption events happen in Resumed state, the activity will enter
into Paused state and the system will invoke onPause() method.
• After an activity returned from Paused state to Resumed state, the system again will
call onResume() method due to this we need to implement onResume() method to
initialize the components that we release during onPause() method
• Following is the example of defining a onResume() method in android activity.

@Override
public void onResume() {
super.onResume();
if (mCamera == null) {
initializeCamera();
}}
DDWD2713 – Mobile Programming 4

4. onPause()
• Whenever the user leaves an activity or the current activity is being Paused then the
system invokes onPause() method.
• Following is the example of defining a onPause() method in android activity.

@Override
public void onPause() {
super.onPause();
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}

• After completion of onPause() method execution, the next method is either


onStop() or onResume() depending on what happens after an activity entered into
a Paused state.

5. onStop()
• The system will invoke onStop() callback method when an activity no longer visible to
the user, the activity will enter into Stopped state.
• The onStop() method is useful to release all the app resources which are no longer
needed to the user.
• Following is the example of defining a onStop() method in android activity.

@Override
protected void onStop()
{
super.onStop();
}
• The next callback method which raised by the system is either onRestart(), in case if
the activity coming back to interact with the user or onDestroy(), in case if the
activity finished running.
DDWD2713 – Mobile Programming 5

6. OnRestart()
• The system will invoke onRestart() method when an activity restarting itself after
stopping it. The onRestart() method will restore the state of activity from the time
that is being stopped.

• The onRestart() callback method in android activity will always be followed


by onStart() method.

7. onDestroy()
• The system will invoke onDestroy() method before an activity is destroyed and this is
the final callback method received by the android activity.

• The system will invoke this onDestory() callback method either the activity is finishing
or system destroying the activity to save space.

• Following is the example of defining a onDestroy() method in android activity.

@Override
public void onDestroy()
{
super.onDestroy();
}

• The onDestroy() method will release all the resources which are not released by
previous callback onStop() method.
DDWD2713 – Mobile Programming 6

Android Activity Lifecycle Diagram

Following is the pictorial representation of the Android Activity Life cycle which shows how
Activity will behave in different stages using callback methods.
DDWD2713 – Mobile Programming 7

Android Activity Lifecycle Example


Following is the example of invoking activity callback methods to see the life cycle process of
activity in android application.

MainActivity.java File Code

package com.tutlane.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Activity Lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("Activity Lifecycle","onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("Activity Lifecycle","onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("Activity Lifecycle","onPause invoked");
}

@Override
protected void onStop() {
super.onStop();
Log.d("Activity Lifecycle","onStop invoked");
}
DDWD2713 – Mobile Programming 8

@Override
protected void onRestart() {
super.onRestart();
Log.d("Activity Lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("Activity Lifecycle","onDestroy invoked");
}
}

• Android can log and display various types of errors/warnings


• Error logging is in Log class of android.util package
• import android.util.Log;
• Turn on logging of different message types by calling
• appropriate method
• Logged errors/warnings displayed in Android Studio window
DDWD2713 – Mobile Programming 9

1. Output of Android Activity Lifecycle Example

2. Now click on Home button in Android Emulator, immediately activity entered


into Paused state and system will invoke onPause() method like as shown below.
DDWD2713 – Mobile Programming 10

3. After a while, the activity will enter into Stopped state and system will
invoke onStop() method like as shown below.

4. Now again launch our app from the Home screen list of apps like as shown below.
DDWD2713 – Mobile Programming 11

5. If you observe log messages in the LogCat window


again onRestart, onStart and onResume methods are invoked by system like as
shown below.

6. Now click on Back button in the android emulator, the system will invoke
the onPause method and after a while onStop, onDestroy methods will be invoked
like as shown below.

Here we need to remember that onCreate and onDestroy methods will invoke only
once throughout the activity life cycle.
DDWD2713 – Mobile Programming 12

This is how android activity life cycle process will invoke different methods while
transition from one stage to another stage.

Running App
• A running app is one that user is currently using or interacting with
• Visible, in foreground
DDWD2713 – Mobile Programming 13

Paused App
• An app is paused if it is visible but no longer in foreground
o E.g. blocked by a pop-up dialog box
• App’s onPause( ) method is called during transition from running to paused state
• Typical actions taken in onPause( ) method

o Stop animations or CPU intensive tasks


o Stop listening for GPS, broadcast information
o Release handles to sensors (e.g GPS, camera)
o Stop audio and video if appropriate

Paused

Running
DDWD2713 – Mobile Programming 14

Resuming Paused App


• A paused app resumes running if it becomes fully visible and in foreground
o E.g. pop-up dialog box blocking it goes away
• App’s onResume( ) method is called during transition from paused to running state
o Restart videos, animations, GPS checking, etc

Paused
DDWD2713 – Mobile Programming 15

Stopped App
• An app is stopped if it no longer visible and no longer in foreground
o E.g. user starts using another app
• App’s onStop( ) method is called during transition from paused to stopped state
• An activity is stopped when:
o User receives phone call
o User starts a new application
o Activity 1 launches new Activity 2
o Activity instance and variables of stopped app are retained but no code is
being executed by the activity
• If activity is stopped, in onStop( ) method, well behaved apps should
o save progress to enable seamless restart later
o Release all resources, save info (persistence)
DDWD2713 – Mobile Programming 16

• A stopped app can go back into running state if becomes visible and in foreground
• App’s onStart( ) and onResume( ) methods called to transition from stopped to
running state

Running
DDWD2713 – Mobile Programming 17

Starting New App

• To start new app, app is launched


• App’s onCreate( ), onStart( ) and onResume( ) methods are called
• Afterwards new app is running
DDWD2713 – Mobile Programming 18

Rotating Device
• Rotating device (e.g. portrait to landscape) kills current activity and creates new
activity in landscape mode
• Rotation changes device configuration
• Device configuration: screen orientation/density/size, keyboard type, dock mode,
language, etc.
• Apps can specify different resources (e.g. XML layout files, images) to use for
different device configurations
• E.g. use different app layouts for portrait vs landscape screen orientation
DDWD2713 – Mobile Programming 19

Rotating Device: Using Different Layouts


• When device in landscape, uses layout (XML) file in res/layout-land/
• Copy XML layout file (activity_quiz.xml) from res/layout to res/layout-land/ and
tailor it
• When configuration changes, current activity destroyed, onCreate (setContentView
(R.layout.activity_quiz) called again

• Go to app > src > main > res > right-click > New > Android Resource Directory

• Select Resource type as layout then go to Orientation and then click on the >> icon.
DDWD2713 – Mobile Programming 20

• Now in the Screen orientation select Landscape and the directory name automatically
change to layout-land and let the Directory name as layout-land and don’t change it.
DDWD2713 – Mobile Programming 21

Change into Project view

Copy your xml file from res/layout


and paste into res/layout-land
DDWD2713 – Mobile Programming 22

Landscape view – you can adjust your layout to suit


landscape orientation

Saving State Data

• App may be destroyed


o On its own by calling finish
o If user presses back button
• Before Activity destroyed, system calls onSaveInstanceState
• Saves state required to recreate Activity later
o E.g. Save current positions of game pieces
DDWD2713 – Mobile Programming 23

• Systems write info about views to Bundle other (app-specific) information must be saved by
programmer
o E.g. board state in a board game such as mastermind
• When Activity recreated Bundle sent to onCreate and onRestoreInstanceState()
• Can use either method to restore state data/ instance variables

Can restore state data in either method

• Since rotation causes activity to be destroyed and new one created, values of variables lost
or reset
• To stop lost or reset values, save them using onSaveInstanceState() before activity is
destroyed
o E.g. called before portrait layout is destroyed
• System calls onSaveInstanceState before onPause( ), onStop( ) and onDestroy( )
• For example, if we want to save the value of a variable mCurrentIndex during rotation
• First, create a constant as a key for storing data in the bundle
• Then override onSaveInstanceState() method to store the data
• Override OnRestoreInstanceState() method to retrieve the data
DDWD2713 – Mobile Programming 24

1. declare constant key

2. store the data

3. retrieve the data


DDWD2713 – Mobile Programming 25

Creating UI programmatically
You can create user interface components such as layouts at runtime programmatically

1. First, create a LinearLayout object to contain all the views in the activity.

1. //Create a layout---------------
2. LinearLayout linearLayout = new LinearLayout(this);
3. linearLayout.setOrientation(LinearLayout.VERTICAL);

2. In this example, the activity will not be loaded from the main.xml file, as it is by default in
any Android Application.
First, we created a LayoutParams object to specify the layout parameter, which can be used
by other views.

//Create params for views---------------


LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.
WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 20);
layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;

3. Now, you need to create some UI elements like EditText, TextView, Button, CheckBox,
RadioGroup and RadioButton etc.

1. //----Create a Button------
2. Button myButton = new Button(this);
3. myButton.setText( "Press Me");
4. myButton.setBackgroundColor(Color.CYAN);
5. myButton.setPadding(20, 20, 20, 20);
6.
7. //----Create a TextView------
8. TextView myText = new TextView(this);
9. myText.setText("I am a TextView");
10. myText.setTextSize(20);
11. myText.setBackgroundColor(Color.MAGENTA);
12.
13. //----Create an EditText------
14. EditText myInput = new EditText(this);
15. myInput.setHint("I am an EditText");
16. myInput.setBackgroundColor(Color.YELLOW);
DDWD2713 – Mobile Programming 26

17. myInput.setWidth(layoutParams.WRAP_CONTENT);

All the elements created above are added to the LinearLayout object.
1. //---Add all elements to the layout
2. linearLayout.addView(myButton,layoutParams);
3. linearLayout.addView(myText,layoutParams);
4. linearLayout.addView(myInput);

Subsequently, it is added to the activity, as shown below.


1. this.addContentView(linearLayout,layoutParams);
DDWD2713 – Mobile Programming 27

References
1. Android Nerd Ranch, 1st edition
2. Busy Coder’s guide to AŶdroid versioŶ 4.4
3. CS 65/165 slides, Dartmouth College, Spring 2014
4. CS 371M slides, U of Texas Austin, Spring 2014
5. Slides from Prof. Emmanuel Agu, Worcester Polytechnic Institute, CS 528, Mobile and
Ubiquitous Computing Class, Fall 2017
6. 2017 J.F. DiMarzio, Beginning Android Programming with Android Studio, 4th Edition,
Indianapolis, Indiana

You might also like