3 - Menus and Dialog Box
3 - Menus and Dialog Box
3 - Menus and Dialog Box
TECHNOLOGIES
Lecture 3
Android Menus,
Using Dialog Box
• UI Patterns help users to navigate through every app in the same way.
• Option menus
onCreateOptionsMenu()
onOptionItemsSelected()
• Context menus
onCreateContextMenu()
onContextItemsSelected()
Using an Option Menu
1. Create the menu XML file
2. Add Menu Resources
3. Add Menu items
…
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Using an Option Menu
5. Process the menu action in onMenuItemSelected of Activity
@Override
public boolean onOptionItemSelected(int featureId, MenuItem item) {
if (item.id == R.id.menu_item1){
…
}
return true;
}
• menu.xml
…
<item
android:id="@+id/action_add"
android:icon="@android:drawable/ic_menu_add"
android:orderInCategory="0"
android:showAsAction="always"/>
…
• java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
menu.findItem(R.id.item1).setIntent(new Intent(this,
FullscreenActivity.class));
…
return true;
}
Using a Context Menu
3. Override onCreateContextMenu
4. Inflate (load) the menu layout resource into the context
menu
Using a Context Menu
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu,v,menuInfo);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate( R.menu.context_menu, menu );
}
Using a Context Menu
5. Process the menu action in onContextItemSelected of Activity
@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_item1){
…
}
return super.onContextItemSelected(item);
}
Dialogs
The dialog box (also known as a dialog) is an onscreen element that offers
choices to the user.
Dialog
AlertDialog
CharacterPickerDialog
ProgressDialog
TimePickerDialog
DatePickerDialog
Dialogs
Key methods that an activity use
to manage a Dialog Instance
onCreateDialog
A callback when a dialog is being created for the first time.
onPrepareDialog
A callback for updating a dialog on-the fly
showDialog()
Used to display a Dialog instance.
dismissDialog()
Used to stop showing a Dialog instance
removeDialog()
Used to remove a Dialog instance from the Activity object’s Dialog pool.
Working with Custom Dialog
1. Design a custom layout resource to display in AlertDialog
2. Define the custom dialog identifier in the activity
3. Update the Activity class’ onCreateDialog() method to build and
return the appropriate custom AlertDialog
4. Launch the dialog using the showDialog() method
Example:
LayoutInflater inflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.custom_dialog, null);