Android Basic CourseCreating layout classes by using source code – xml layout built-in source code public class HelloAndroid extends Activity { /** Called when the activity is first cre
Trang 1Android Basic Course
M.Sc Bui Tan Loc btloc@fit.hcmus.edu.vn
Department of Software Engineering, Faculty of Information Technology, University of Science – Ho Chi Minh City, Viet Nam
Module 4: User Interfaces
Section 2: Activity
Trang 2Android Basic Course
High-level diagram class of the Android View API
2
View
ViewGroup Activity
Trang 3Android Basic Course
Objectives
• After completing this section, you will able to:
• Create an activity with loading layout form xml-based layout file
• Manage the activity lifecycle
• Start or shut down an activity
• Create resources of many types of menus
• Handle menu item selections
• Use event handlers
• Use event listeners
3
Trang 4Android Basic Course
Contents
• Activity overview
• Activity skeleton code
• Activity lifecycle
• Different types of menus
• Creating a menu resource
• Common Activity’s methods for working with menus
• Common Menu’s methods for working with submenus
• Common MenuItem’s methods for working with menu items
• User Input events
• Using event handlers
4
Trang 5Android Basic Course
activity for reading emails
called views
how they interact with each other and with other applications.
5
Trang 6Android Basic Course
Designing layout by using xml layout text editor
<?xml version="1.0" encoding="utf-8"?>
Trang 7Android Basic Course
Designing layout by using xml layout GUI editor
7
Trang 8Android Basic Course
Loading layout from xml-based layout file
package com.example.helloandroid;
import android.app Activity ;
import android.os Bundle ;
public class HelloAndroid extends Activity { /** Called when the activity is first created */
Trang 9Android Basic Course
Creating layout classes by using source code – xml layout built-in source code
public class HelloAndroid extends Activity {
/** Called when the activity is first created */
@Override
public void onCreate( Bundle savedInstanceState) {
super onCreate(savedInstanceState);
TextView tv = new TextView ( this );
tv.setText( "Hello, Android" );
LinearLayout linear;
linear = new LinearLayout( this );
linear.setOrientation( LinearLayout VERTICAL );
linear.setLayoutParams(new LayoutParams ( LayoutParams FILL_PARENT , LayoutParams FILL_PARENT ));
linear.addView(tv);
setContentView(linear);
}
9
Trang 10Android Basic Course
High-level diagram of activity
• Views and other Android components use strings, colors, styles, and graphics, which are compiled into a binary form and made available to applications as resources
• The automatically generated R.java provides a reference to individual resources and is the bridge between binary references and the source code of an Android
10
Trang 11Android Basic Course
Activity skeleton code
public class ExampleActivity extends Activity { @Override
public void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// The activity is being created.
} @Override
protected void onStart() { super.onStart();
/ / The activity is about to become visible.
} @Override
protected void onResume() { super.onResume();
// The activity has become visible (it is now "resumed").
}
…
11
Trang 12Android Basic Course
Activity skeleton code
protected void onStop() { super.onStop();
// The activity is no longer visible (it is now "stopped")
} @Override
protected void onDestroy() { super.onDestroy();
// The activity is about to be destroyed.
}
12
Trang 13Android Basic Course
The activity lifecycle
13
Trang 14Android Basic Course
Android Activity main lifecycle methods and their purpose
onCreate() Called when the Activity is created Setup is done here Also provided is
access to any previously stored state in the form of a Bundle.
onRestart() Called if the Activity is being restarted, if it’s still in the stack, rather
than starting new.
onStart() Called when the Activity is becoming visible on the screen to the user.
onResume() Called when the Activity starts interacting with the user (This method
is always called, whether starting or restarting.) onPause() Called when the Activity is pausing or reclaiming CPU and other
resources This method is where you should save state information so that when an Activity is restarted, it can start from the same state it was in when it quit
onStop() Called to stop the Activity and transition it to a nonvisible phase and
14
Trang 15Android Basic Course
Another activity lifecycle diagram
• In the foreground phase , the Activity is viewable on the screen and is on top of everything else.
• In the visible phase , the Activity is on the screen, but it might not be on top and interacting with the user.
• The entire lifecycle phase refers to the methods that might be called when the application isn’t on the screen,
15
Trang 16Android Basic Course
The onSaveInstanceState() function
• Whenever an activity is about to be killed, the
onSaveInstanceState() function is called Override this
to save relevant information that should be retained.When the activity is then recreated, the
function (or onCreate() ) to retrieve the saved information.
• The onSaveInstanceState() function is distinct from
in front of the activity, the onPause() function is called Later, if the activity is still paused when the OS needs
to reclaim resources, it calls onSaveInstanceState()
16
Trang 17Android Basic Course
Activity Life Cycle Sample
• Open Child Activity
> onCreate(null) -> onStart() -> onResume() -> [Open Child Activity]
> onSaveInstanceState() -> onPause() -> onStop() -> [Close Child Activity]
> onRestart() -> onStart() -> onResume()
• Transparent View
> onCreate(null) -> onStart() -> onResume() -> [Open Transparent View]
> onSaveInstanceState() -> onPause() -> [Close Transparent View]
> onResume()
• Turn Display
> onCreate(null) -> onStart() -> onResume() -> [Turn Display]
> onSaveInstanceState() -> onPause() -> onStop() -> onDestroy() ->
[Recreate]
> onCreate() -> onStart() -> onRestorInstanceState() -> onResume()17
Trang 18Android Basic Course
Activity Life Cycle Sample
> onCreate(null) -> onStart() -> onResume() -> [Home Button]
> onSaveInstanceState() -> onPause() -> onStop() -> [Start App]
> onRestart() -> onStart() -> onResume()
• Phone call interrupt
> onCreate(null) -> onStart() -> onResume() -> [Phone Call]
> onSaveInstanceState() -> onPause() -> onStop() -> [Hang Up or press Back]
> onRestart() -> onStart() -> onResume()18
Trang 19Android Basic Course
Starting an activity for passing no values
• Starting an activity for passing no values:
Intent intent = new Intent ( this , SignInActivity class );
startActivity(intent);
19
Trang 20Android Basic Course
Starting an activity for passing values
• Starting an activity for passing values by putting values into intent object:
//SignInActivity
public static final String NAME_KEY = “name” ;
public static final String PASS_KEY = “pass” ;
…
Intent intent = new Intent ( this , OrderActivity class );
intent.putExtra( this NAME_KEY , nameValue);
intent.putExtra( this PASS_KEY , passValue);
startActivity(intent);
20
Trang 21Android Basic Course
Catching passed values
//OrderActivity
…public void OnCreate(…){
Bundle extras = getIntent().getExtras();
String usrName = extras.getString(SignInActivity.NAME_KEY);
String passWord = extras.getString(SignInActivity.PASS_KEY);
…}21
Trang 22Android Basic Course
Starting an activity for results
//NoteList Activity
public static final int ACTIVITY_CREATE = 0;
public static final int ACTIVITY_EDIT = 1;
…//Open creating note screen
Intent i = new Intent(this, NoteEdit.class);
startActivityForResult(i, ACTIVITY_CREATE);
…//Open editing note screen
Intent i = new Intent(this, NoteEdit.class);
startActivityForResult(i, ACTIVITY_EDIT);
…22
Trang 23Android Basic Course
Catching returned results
mDbHelper.updateNote(mRowId, editTitle, editBody);
} fillData();
23
Trang 24Android Basic Course
Shutting Down an Activity
• Returning no results:
finish();
• Returning result cancelled:
setResult( RESULT_CANCELLED , null );
finish();
• Returning result ok:
Intent mIntent = new Intent ();
mIntent.putExtras(…);
setResult( RESULT_OK , mIntent);
24
Trang 25Android Basic Course
Shutting Down an Activity
• You can also shut down a separate activity that you previously started by calling finishActivity() This method is used for shutting down an activity being in the foreground.
startActivityForResult(intent, requestCode);
try { Thread.sleep(3500);
}
catch (InterruptedException e) { e.printStackTrace();
}finishActivity(requestCode);
25
Trang 26Android Basic Course
Different types of menus
an activity, which appears when the user touches the MENU button.
• Android 3.0 or later provides the Action Bar, as "action items” to quick access to select menu items
when the user touches and holds a view that's registered to provide a context menu.
when the user touches a menu item that contains a nested menu.
26
Trang 27Android Basic Course
Different types of menus
27
Trang 28Android Basic Course
Creating a menu resource
• To create a menu resource, create an XML file inside your project's res/menu/ directory and build the menu with the following elements:
• <menu>: Defines a Menu, which is a container for menu items A
<menu> element must be the root node for the file and can hold one
or more <item> and <group> elements
• <item>: Creates a MenuItem, which represents a single item in a menu This element may contain a nested <menu> element in order to create a submenu
• <group>: An optional, invisible container for <item> elements It allows you to categorize menu items so they share properties such
as active state and visibility
28
Trang 29Android Basic Course
Creating a resource of menus
Trang 30Android Basic Course
Creating a resource of menus with submenus
<? xml version ="1.0" encoding = "utf-8" ?>
Trang 31Android Basic Course
Creating a resource of menu groups
<?xml version="1.0" encoding="utf-8" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/item1"
android:icon="@drawable/item1"
android:title="@string/item1" />
<group android:id="@+id/group1" >
<item android:id="@+id/groupItem1"
Trang 32Android Basic Course
Creating a resource of checkable menu items
<menu
xmlns:android="http://schemas.android.com/apk/res/android" >
<group android:checkableBehavior="single" >
<item android:id="@+id/red"
Trang 33Android Basic Course
Common Activity’s methods for working with menus
• Creating menu items:
Trang 34Android Basic Course
Common Menu’s methods for working with submenus
• A menu group is a collection of menu items that share certain traits With a group, you can:
• Show or hide all items with setGroupVisible()
• Enable or disable all items with setGroupEnabled()
• Specify whether all items are checkable with setGroupCheckable()
34
Trang 35Android Basic Course
Common MenuItem’s methods for working with menu items
Trang 36Android Basic Course
Loading an options menu resource – Inflating an options menu resource
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;}
36
Trang 37Android Basic Course
Loading a context menu resource – Inflating a context menu resource
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
• In order for a View to provide a context menu, you must "register" the view for a context menu Call registerForContextMenu() and pass it the View you want to give a context menu When this View then receives a long-press, it displays a context menu.
• If your activity uses a ListView and you want all list items to provide a context menu, register all items for a context menu by passing the ListView to
registerForContextMenu() For example, if you're using a ListActivity , at the very end of the onCreate() method add this line:
• registerForContextMenu ( getListView() );
37
Trang 38Android Basic Course
Handling options menu selections
@Override
public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection
switch (item.getItemId()) { case R.id.new_game:
newGame();
return true; case R.id.help:
showHelp();
return true; default:
return super.onOptionsItemSelected(item);
38
Trang 39Android Basic Course
Handling context menu selections
@Override
public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) { case R.id.edit:
editNote(info.id);
return true; case R.id.delete:
deleteNote(info.id);
return true; default:
return super.onContextItemSelected(item);
}
39
Trang 40Android Basic Course
Handling checkable menu items
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.vibrate:
case R.id.dont_vibrate:
if (item.isChecked()) item.setChecked(false);
else
item.setChecked(true);
return true;
default: return super.onOptionsItemSelected(item);
40
or ContextItem
Trang 41Android Basic Course
Creating menus by using code
static final private int MENU_ITEM = Menu FIRST;
// Unique menu item identifier Used for event handling.
int menuItemId = MENU_ITEM;
// The order position of the item
int menuItemOrder = Menu NONE;
// Text to be displayed for this menu item.
int menuItemText = R string.menu_item;
// Create the menu item and keep a reference to it.
menuItemOrder, menuItemText);
return true;
41
Trang 42Android Basic Course
Creating menus by using code
// Create a new check box item.
menu.add(0, CHECKBOX_ITEM, Menu NONE, " CheckBox" ).setCheckable(true);
// Create a radio button group.
menu.add(RB_GROUP, RADIOBUTTON_1, Menu NONE, "Radiobutton 1" );
menu.add(RB_GROUP, RADIOBUTTON_2, Menu NONE, "Radiobutton 2" );
menu.add(RB_GROUP, RADIOBUTTON_3, Menu NONE,
"Radiobutton 3" ).setChecked( true );
menu.setGroupCheckable(RB_GROUP, true, true);
// Add a shortcut to this menu item, ‘0’ if using the numeric keypad // or ‘b’ if using the full keyboard.
menuItem.setShortcut( '0' , 'b' );
// or
menuItem.setNumericShortcut( '0' );
42