0% found this document useful (0 votes)
89 views58 pages

L05 - Android Intent and Menu ITP4501 2019

The document discusses Android intents and menus. It describes activities as independent windows that make up an app. Intents are used to start activities and contain an action and optional data. Standard actions like ACTION_VIEW, ACTION_DIAL are used to start common activities like browsers, dialers. The document shows code examples of starting activities with different intents, and includes the app manifest and layout files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views58 pages

L05 - Android Intent and Menu ITP4501 2019

The document discusses Android intents and menus. It describes activities as independent windows that make up an app. Intents are used to start activities and contain an action and optional data. Standard actions like ACTION_VIEW, ACTION_DIAL are used to start common activities like browsers, dialers. The document shows code examples of starting activities with different intents, and includes the app manifest and layout files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 58

Android Intent and Menus

Android Intent and Menus 1


Android Activities
• An activity is the equivalent of a Frame/Window in GUI toolkits.
• It takes up the entire area of the screen (minus the status and
title bars on top).
• An activity defined in the AndroidManifest.xml as the main
entry point into an application.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ict.mobile"
android:versionCode="1"
android:versionName="1.0">

<application android:icon="@drawable/icon" android:label="@string/app_name">


<activity android:name=".StandardIntentExample"
android:label="@string/app_name">
<intent-filter> Main activity
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

• For long running tasks, it’s better to use a service that talks to
this activity.
Android Intent and Menus 2
Activities and Intents
• Activities are independent of each other; however
they usually cooperate exchanging data and actions.
• Typically, one (main) activity that should be
presented to the user when the application is
launched.
• Moving from one activity to another is by executing
an intent.
• An intent is an abstract description of an operation
to be performed.
Intent: { action + data }
Main Sub-
Activity activity1
Optional Results
Android Intent and Menus 3
Invoking Activities
• There are 3 ways to invoke an activity:
1. startActivity(intent)
 launches an Activity
 We will focus on this method

2. sendBroadcast(intent)
 sends an intent to any interested
BroadcastReceiver components

3. startService(intent) or bindService(intent, …)
 communicate with a background Service.
Android Intent and Menus 4
Invoking Activities
• The main arguments of an Intent are:
1. Action The built-in action to be performed,
such as ACTION_VIEW, ACTION_EDIT,
ACTION_MAIN, …or user-created-action
2. Data The primary data to operate on,
such as a person record in the contacts
database (expressed as a Uri).

Intent: { action + data }


Main Sub-
Activity activity1
Optional Results

Android Intent and Menus 5


Invoking Activities
• Typically an intent is called as follows:

Intent myActivity= new Intent(action, data);


startActivity(myActivity);

Built-in or user-
Primary data (as an URI)
created Action
tel://
http://
sendto://

Android Intent and Menus 6


Standard Activity Actions
• Below are the standard actions that Intent defines for
launching activities (usually through startActivity(Intent).
ACTION_MAIN ACTION_SENDTO
ACTION_VIEW ACTION_ANSWER
ACTION_ATTACH_DATA ACTION_INSERT
ACTION_EDIT ACTION_DELETE
ACTION_PICK ACTION_RUN
ACTION_CHOOSER ACTION_SYNC
ACTION_GET_CONTENT ACTION_PICK_ACTIVITY
ACTION_DIAL ACTION_SEARCH
ACTION_CALL ACTION_WEB_SEARCH
ACTION_SEND ACTION_FACTORY_TEST

Android Intent and Menus 7


Using Standard Actions
• Invoke the browser to view a Webpage
intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.vtc.edu.hk"));
startActivity(intent);

Note: 1. Add to the Manifest a request to use the Internet:


<uses-permission android:name="android.permission.INTERNET" />
2. If behind a proxy, you need to set the proxy server information
for the emulator. Android Intent and Menus 8
Using Standard Actions
• Make a phone call.
intent = new Intent(Intent.ACTION_CALL,
Uri.parse("tel:12345678"));
startActivity(intent);

Note: Needs permission


<uses-permission android:name="android.permission.CALL_PHONE“/>
Android Intent and Menus 9
Using Standard Actions
• Show the dialer with the given number filled in.
intent = new Intent(Intent.ACTION_DIAL,
Uri.parse("tel:12345789"));
startActivity(intent);

Android Intent and Menus 10


Using Standard Actions
• Call google map to display IVE(TY).
intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("geo:22.3425,114.1061?z=17"));
startActivity(intent);

Android Intent and Menus 11


Using Standard Actions
Note: The previous example needs
Google API – can be downloaded with
Eclipse using Android SDK and AVD
Manager.
You also need to set the target of the project and virtual
device.

The Google Maps in Android 2.2 or below has a bug when


run behind a proxy server. Run the program on Android 2.3.3
or above with proxy setting as below:
<android-sdk-path>\tools>emulator -http-proxy http://hqproxy.vtc.edu.h
k:8080 -avd Android2_3_3 Android Intent and Menus 12
Using Standard Actions
• Invoke Google Street View for IVE(TY)
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(

"google.streetview:cbll=22.3432,114.1068&cbp=1,200,,0,1"));
startActivity(intent);

Android Intent and Menus 13


Using Standard Actions
• Show all contacts
intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("content://contacts/people/"));
startActivity(intent);

Note: The 3 contacts (Eddie, Kenny and Nancy) should be added to the
emulator before running the above code.
Android Intent and Menus 14
Using Standard Actions
• Edit the second contact
intent = new Intent(Intent.ACTION_EDIT,
Uri.parse(ContactsContract.Contacts.CONTENT_LOOKUP_URI
+ "/" + 2));
startActivity(intent);

Android Intent and Menus 15


Using Standard Actions
• Call the camera to take photos
intent = new
Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0); Explain later

Note: Needs permission


<uses-permission android:name="android.permission.CAMERA"/>
Android Intent and Menus 16
StandardIntentExample – main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height=“match_parent">

<Button android:id="@+id/CallBrowser" a
ndroid:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Call Browser"
android:onClick="callIntent"></Button>
<Button android:id="@+id/CallSomeone"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Call Someone"
android:width="100px" android:onClick="callIntent"></Button>
<Button android:id="@+id/Dial" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Dial"
android:width="100px" android:onClick="callIntent"></Button>
<Button android:id="@+id/SearchOnMap"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Search On Map"
android:width="100px" android:onClick="callIntent"></Button>
<Button android:id="@+id/StreetView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Street View"
android:width="100px" android:onClick="callIntent"></Button>
. . . . . . Others are skipped

Android Intent and Menus 17


StandardIntentExample – AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ict.mobile"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />

<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:screenOrientation="portrait"
android:name=".StandardIntentExample"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER”/>
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
</manifest>
Android Intent and Menus 18
StandardIntentExample.java (callIntent Method)
public void callIntent(View view) {
Intent intent = null;
switch (view.getId()) {
case R.id.CallBrowser:
intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.vtc.edu.hk"));
startActivity(intent);
break;
case R.id.CallSomeone:
intent = new Intent(Intent.ACTION_CALL,
Uri.parse("tel:12345678"));
startActivity(intent);
break;

//. . . . . . Other cases are skipped

case R.id.TakePicture:
intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
break;
default:
break;
}
}

Android Intent and Menus 19


Starting Activities and Getting Results
• The startActivity(Intent) method is used to
start a new activity, which will be placed at the top
of the activity stack.
• Sometimes you want to get a result back from the
called sub-activity when it ends.
• For example, you may start an activity that let the
user pick a person from a list of contacts; when it
ends, it returns the person that was selected.

Android Intent and Menus 20


Starting Activities and Getting Results
• In order to get results back from the called activity
we use the method
startActivityForResult (Intent, requestCodeID)
where the second (requestCodeID) parameter
identifies the call.
• The result sent by the sub-activity could be picked
up through the asynchronous method
onActivityResult (
requestCodeID, resultCode, Intent)

Android Intent and Menus 21


Starting Activities and Getting Results
• Before an activity exits, it can call
setResult(resultCode) to return a termination signal
back to its parent.
• Always supply a result code, which can be the
standard results Activity.RESULT_CANCELED,
Activity.RESULT_OK, or any custom values.
• All of this information can be capture back on the
parent's
onActivityResult(int requestCodeID,
int resultCode, Intent data)
along with the integer identifier it originally supplied.
• If a child activity fails for any reason (such as
crashing), the parent activity will receive a result
with the code RESULT_CANCELED.

Android Intent and Menus 22


Starting Activities and Getting Results

Intent: {action + data +


requestCodeID}
Activity 2
Activity 1 setResult()

startActivityForResult()

onActivityResult()

requestCodeID
resultCode
optional data

Android Intent and Menus 23


Example - IntentResultExample
1. Main-activity calls the Contacts Activity to show all
contacts and pick a particular one
(Intent.ACTION_PICK).
2. Return the URI identifying the person we want to call
(content://contacts/people/n) to the main- Activity.
3. Then pass the selected contact’s entry to another built-
in activity for calling, sms or emailing actions
(Intent.ACTION_VIEW).

Android Intent and Menus 24


Android Intent and Menus 2
5
Example - IntentResultExample
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/label1" android:layout_width="match_parent"
android:layout_height="wrap_content" android:background="#ff0000cc"
android:text="This is Activity1" android:textStyle="bold"
android:textSize="20sp"/>
<EditText android:id="@+id/text1" android:layout_width="match_parent"
android:layout_height="54px" android:text="content://contacts/people/"
android:textSize="18sp"/>
<Button android:id="@+id/btnPickContact" android:layout_width="149px"
android:layout_height="wrap_content" android:text="Pick a Contact"
android:textStyle="bold"
android:onClick="callIntent"/>
</LinearLayout>

Android Intent and Menus 26


Example - IntentResultExample
public class IntentResultExample extends ActionBarActivity {
TextView label1;
EditText text1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
label1 = findViewById(R.id.label1);
text1 = findViewById(R.id.text1);
}

public void callIntent(View view) {


Intent intent = null;
switch (view.getId()) {
case R.id.btnPickContact:
intent = new Intent(Intent.ACTION_PICK,
Uri.parse("content://contacts/people/"));
// start myActivity2.
// Tell it that our requestCodeID (or nickname) is 888
startActivityForResult(intent, 888);
break;
default:
break;
}
}
Android Intent and Menus 27
Example - IntentResultExample
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// use requestCodeto find out who is talking back to us
switch (requestCode) {
case (888): {
// 888 is our friendly contact-picker activity
if (resultCode == Activity.RESULT_OK) {
String selectedContact = data.getDataString();
label1.setText(selectedContact.toString());
Intent myAct3 = new Intent(Intent.ACTION_VIEW,
Uri.parse(selectedContact));
startActivity(myAct3);
} else {
// user pressed the BACK button
label1.setText("Selection CANCELLED " + requestCode + " "
+ resultCode);
}
break;
}
}// switch
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}// onActivityResult
} Android Intent and Menus 28
Intent – Passing More Data
1. Intent allows the passing of additional information to
the sub-activity.
2. It provides a series of putExtra() and getXXXExtra()
(XXX is the data type, e.g. getDoubleExtra) methods for
storing and reading extra data which is represented by a
key-value pair.

Activity 1 Activity 2
v1 = i.getXXXExtra(“key1”)
v2 = i.getXXXExtra(“key2”)
i1.putExtra(“key1”, value1)
i1.putExtra(“key2”, value2)
startActivityForResult()
i2.putExtra(“r1”, value3)
i2.putExtra(“r2”, value4)
onActivityResult()
setResult()
v1 = i.getXXXExtra(“r1”)
v2 = i.getXXXExtra(“r2”)
Android Intent and Menus 29
Example - IntentData
1. Activity1 passes two data - ("Value1", "Value one from
Activity1“) and ("Value2", "Value two from Activity1") to
Activity2.
2. Activity2 returns a string data ("returnKey1", "Swinging
on a star.") to Activity1 .

Activity1 Activity2 Activity1

Android Intent and Menus 3


0
Example - IntentData
(main1.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView android:id="@+id/TextView01" android:layout_width="match_parent"


android:layout_height="wrap_content"
android:text="First Activity. Press button to call second activity"
android:minHeight="60dip" android:textSize="20sp"></TextView>
<Button android:id="@+id/Button01" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:onClick="onClick"
android:text="Calling an intent"></Button>
<TextView android:id="@+id/TextView02" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="Result from Activity2:"
android:minHeight="60dip" android:textSize="20sp"></TextView>
</LinearLayout>

Android Intent and Menus 31


Example - IntentData
(main2.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="First value from Activity1"></TextView>
<EditText android:id="@+id/EditText01"
android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Second Value from Activity1"></TextView>
<EditText android:id="@+id/EditText02"
android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
<Button android:id="@+id/Button01" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:onClick="onClick"
android:text="Finish this activity"></Button>
</LinearLayout>

Android Intent and Menus 32


Example - IntentData (AndroidManifest.xml)
• Need to add the new activity Activity2 to the file
AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ict.mobile"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />

<application android:icon="@drawable/icon" android:label="@string/app_name">


<activity android:name="Activity1"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Activity2"></activity>
</application>
</manifest>
Android Intent and Menus 33
Example - IntentData (Activity1.java)
public class Activity1 extends ActionBarActivity {
private static final int REQUEST_CODE = 3434;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
}
public void onClick(View view) {
Intent i = new Intent(this, Activity2.class);
i.putExtra("Value1", "Value one from Activity1 ");
i.putExtra("Value2", "Value two from Activity1");
startActivityForResult(i, REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
if (data.hasExtra("returnKey1")) {
TextView tv = (TextView) findViewById(R.id.TextView02);
tv.setText("Result from Activity 2:\n"
+ data.getExtras().getString("returnKey1"));
}
}
}
} Android Intent and Menus 34
Example - IntentData (Activity2.java)
public class Activity2 extends ActionBarActivity {
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main2);
EditText text1 = findViewById(R.id.EditText01);
EditText text2 = findViewById(R.id.EditText02);
text1.setText(getIntent().getStringExtra("Value1"));
text2.setText(getIntent().getStringExtra("Value2"));
}

public void onClick(View view) {


finish();
}

@Override
public void finish() {
Intent data = new Intent();
data.putExtra("returnKey1", "Swinging on a star. ");
setResult(RESULT_OK, data);
super.finish();
}
}
Android Intent and Menus 35
Menus
• Menus are an important part of an activity's user
interface, which provide users a familiar way to
perform actions.

• There are three types of application menus:


• Options Menu
• Context Menu
• Submenu

Android Intent and Menus 36


Options Menu
• The primary collection of menu items for an activity,
which appears when the user touches the MENU
button.

Menu button

Android Intent and Menus 37


Options Menu
• The Options Menu is where you should include basic
activity actions and necessary navigation items (for
example, a button to open the application settings).

Android Intent and Menus 38


Options Menu
• When the Android system creates the Options Menu for
the first time, it calls your activity's
onCreateOptionsMenu() method.

• You can populate the menu in code, using add() to add


items to the menu.

• When the user selects a menu item from the Options, the
system calls your activity's onOptionsItemSelected()
method.

• You can identify the menu item by calling getItemId(),


which returns the unique ID for the menu.

Android Intent and Menus 39


Options Menu
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<EditText
android:id="@+id/etMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:inputType="text"
android:text="@string/hello" />

</LinearLayout>

Android Intent and Menus 40


Options Menu
MenuExample.java
package com.exercise.android;

import android.support.v7.app.ActionBarActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;

public class MenuExample extends ActionBarActivity {


/** Called when the activity is first created. */

EditText etMessage;
Integer[] ayPointSize = {10, 20, 30, 40, 50};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etMessage = (EditText)findViewById(R.id.etMessage);
}

Android Intent and Menus 41


Options Menu
MenuExample.java
// populate the Option menu
public boolean onCreateOptionsMenu(Menu menu) {
// arguments: groupId, itemId, orderId, title
menu.add(0, 1, 1, "10 points");
menu.add(0, 2, 2, "20 points");
menu.add(0, 3, 3, "30 points");
menu.add(0, 4, 4, "40 points");
menu.add(0, 5, 5, "50 points");
menu.add(0, 6, 6, "Red Text");
menu.add(0, 7, 7, "Green Text");
menu.add(0, 8, 8, "Blue Text");
return super.onCreateOptionsMenu(menu);
}

// called whenever an item is selected


public boolean onOptionsItemSelected(MenuItem item){
return (applyMenuOption(item) ||
super.onOptionsItemSelected(item));
}

Android Intent and Menus 42


Options Menu
MenuExample.java
// apply the action associated to selected item
private boolean applyMenuOption(MenuItem item) {
int menuItemId = item.getItemId();

if(menuItemId <= 5)
etMessage.setTextSize(ayPointSize[menuItemId -1]);
else {
if (menuItemId == 6)
etMessage.setTextColor(Color.RED);
else if (menuItemId == 7)
etMessage.setTextColor(Color.GREEN);
else if(menuItemId == 8)
etMessage.setTextColor(Color.BLUE);
}
return false;
}
}

Android Intent and Menus 43


Context Menu
• A floating list of menu items that appears when the
user touches and holds a view that's registered to
provide a context menu.
• You can create a context menu for any View, though
context menus are most often used for items in a
ListView.
• In order for a View to provide a context menu, you
must
• “register” the view for a context menu
registerForContextMenu()
• build the Context Menu
onCreateContextMenu()
• When the user selects an item from the context
menu, the system calls onContextItemSelected().
Android Intent and Menus 44
Context Menu
Long-press an
editText to invoke its
Content Menu

Android Intent and Menus 45


Context Menu
MenuExample.java
package com.exercise.android;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;

public class L4Activity extends Activity {


/** Called when the activity is first created. */

EditText etMessage;
Integer[] ayPointSize = {10, 20, 30, 40, 50};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etMessage = (EditText)findViewById(R.id.etMessage);
registerForContextMenu(etMessage);
}
Android Intent and Menus 46
Context Menu
MenuExample.java
...

public boolean onCreateOptionsMenu(Menu menu) {


// arguments: groupId, itemId, orderId, title
menu.add(0, 1, 1, "10 points");
menu.add(0, 2, 2, "20 points");
...
return super.onCreateOptionsMenu(menu);
}

public void onCreateContextMenu(ContextMenu menu,


View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, 9, 1, "Normal");
menu.add(0, 10, 2, "Bold");
menu.add(0, 11, 3, "Italic");
}

Android Intent and Menus 47


Context Menu
MenuExample.java
...

// called whenever an item is selected


public boolean onOptionsItemSelected(MenuItem item){
return (applyMenuOption(item) ||
super.onOptionsItemSelected(item));
}

public boolean onContextItemSelected(MenuItem item) {


return (applyMenuOption(item) ||
super.onContextItemSelected(item));
}

Android Intent and Menus 48


Context Menu
MenuExample.java
// apply the action associated to selected item
private boolean applyMenuOption(MenuItem item) {
int menuItemId = item.getItemId();

if(menuItemId <= 5)
etMessage.setTextSize(ayPointSize[menuItemId -1]);
else {
if (menuItemId == 6)
etMessage.setTextColor(Color.RED);
else if (menuItemId == 7)
etMessage.setTextColor(Color.GREEN);
else if(menuItemId == 8)
etMessage.setTextColor(Color.BLUE);
else if(menuItemId == 9)
etMessage.setTypeface(Typeface.DEFAULT, 0);
else if(menuItemId == 10)
etMessage.setTypeface(Typeface.DEFAULT, 1);
else if(menuItemId == 11)
etMessage.setTypeface(Typeface.DEFAULT, 2);
}
return false;
}

Android Intent and Menus 49


SubMenu
• A floating list of menu items that appears when the
user touches a menu item that contains a nested
menu.
• You can add a submenu to any menu (except a
submenu).
• Submenus are useful when your application has a lot
of functions that can be organized into topics.
• You can also use addSubMenu() to dynamically add
a SubMenu to an existing Menu. This returns the
new SubMenu object, to which you can add
submenu items, using add().

Android Intent and Menus 50


SubMenu

Android Intent and Menus 51


SubMenu
MenuExample.java
public boolean onCreateOptionsMenu(Menu menu) {
// arguments: groupId, itemId, orderId, title
MenuItem item1 = menu.add(0, 1, 1, "10 points");
MenuItem item2 = menu.add(0, 2, 2, "20 points");
MenuItem item3 = menu.add(0, 3, 3, "30 points");
MenuItem item4 = menu.add(0, 4, 4, "40 points");
// MenuItem item5 = menu.add(0, 5, 5, "50 points");
menu.add(0, 6, 6, "Red Text");
menu.add(0, 7, 7, "Green Text");
menu.add(0, 8, 8, "Blue Text");

Android Intent and Menus 52


SubMenu
MenuExample.java
public boolean onCreateOptionsMenu(Menu menu) {
...
// add shortcut
item1.setShortcut('1', '1');
item2.setShortcut('2', '2');
item3.setShortcut('3', '3');
item4.setShortcut('4', '4');
//item5.setShortcut('5', '5');

// adding a sub-menu as 5th entry


SubMenu sm5 = menu.addSubMenu(0, 5, 5, "Sub-Menu-DEMO");

sm5.add(0, 5, 1, "Sub Menu 5-1");


sm5.add(0, 5, 2, "Sub Menu 5-2");
sm5.add(0, 5, 3, "Sub Menu 5-3");

return super.onCreateOptionsMenu(menu);
}

Android Intent and Menus 53


SubMenu
MenuExample.java
// apply the action associated to selected item
private boolean applyMenuOption(MenuItem item) {
int menuItemId = item.getItemId();

if(menuItemId < 5)
etMessage.setTextSize(ayPointSize[menuItemId -1]);
else if(menuItemId == 5)
etMessage.setText("You have selected: \n" + item.getTitle());
else if (menuItemId == 6)
etMessage.setTextColor(Color.RED);
else if (menuItemId == 7)
etMessage.setTextColor(Color.GREEN);
else if(menuItemId == 8)
etMessage.setTextColor(Color.BLUE);
else if(menuItemId == 9)
etMessage.setTypeface(Typeface.DEFAULT, 0);
else if(menuItemId == 10)
etMessage.setTypeface(Typeface.DEFAULT, 1);
else if(menuItemId == 11)
etMessage.setTypeface(Typeface.DEFAULT, 2);
return false;
}

Android Intent and Menus 54


Defining a Menu in XML
• Instead of building a menu in your activity's code,
you can define a menu and all its items in an XML
menu resource.
• To define the menu, create an XML file inside your
project's res/menu/ directory.
• You can inflate your menu resource (defined in
XML) into the Menu provided in the
onCreateOptionsMenu() callback.

Android Intent and Menus 55


Defining a Menu in XML
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}

Android Intent and Menus 56


Defining a Menu in XML

main_menu
<menu
xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:id="@+id/memuItem1"
android:title="Menu Item1"
android:icon="@drawable/emo_im_happy" />
<item android:id="@+id/menuItem2"
android:title="Menu Item2"
android:icon="@drawable/emo_im_sad" >
<!-- submenu -->
<menu>
<item android:id="@+id/subMenuItem1"
android:title="Sub-menu Item1" />
<item android:id="@+id/subMenuItem2"
android:title="Sub-menu Item2" />
</menu>
</item>

</menu>

Android Intent and Menus 57


Defining a Menu in XML
• You can identify the item by calling getItemId(),
which returns the unique ID for the menu item.
• You can match this ID against known menu items
to perform the appropriate action.
// called whenever an item in your options menu is selected
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.menuItem1:
tvMessage.setText("Menu Item1");
return true;
case R.id.subMenuItem1:
tvMessage.setText("Sub-Menu Item1");
return true;
case R.id.subMenuItem2:
tvMessage.setText("Sub-Menu Item2");
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Android Intent and Menus 58

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy