- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Android menus
In this chapter of the Android development tutorial we will work with menus. Menus group available commands of an application. In traditional desktop applications menus are part of a menubar which is located mostly in the top area of the application. Context or popup menus are special cases of menus.
There are three kinds of menus in Android: options menu, context menu, and popup menu. The options menu is the primary collection of menu items for an activity. In the options menu we should have commands that have global impact on the applications. For example a Settings menu. It is displayed either at the top or at the bottom of the activity. The context menu shows menu items in a specific context. For example for ListView
items. It is shown when the user performs a long-click on an element. A popup menu displays a list of items in a vertical list that's anchored to the view that invoked the menu. It appears below the anchor view if there is room, or above the view otherwise. It should relate to regions of content in the activity.
Menus can be created manually by coding or they can be defined in an XML file. If we define our menus in an XML file we use the MenuInflater
object to create menus from the XML file.
Options menu
Our options menu will have two menu items. When we select a menu item a Toast
window is shown with the name of the selected menu item. The options menu is displayed after we click on the menu button.
The manifest file is not modified in this example.

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="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/message" /> </LinearLayout>
In the main.xml
layout file, we have one TextView
widget. It will display a welcome message.
strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">OptionsMenu</string> <string name="message">Demonstrating Options Menu</string> <string name="om1">Settings</string> <string name="om2">Tools</string> </resources>
This is strings.xml
file.
options_menu.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/settings" android:title="@string/om1" /> <item android:id="@+id/tools" android:title="@string/om2" /> </menu>
This is options_menu.xml
file. It defines two menu items. The file is located in the res/menu/
subdirectory.
MainActivity.java
package com.zetcode.opmenu; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Toast; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.settings: Toast.makeText(MainActivity.this, "Settings menu selected.", Toast.LENGTH_SHORT).show(); return true; case R.id.tools: Toast.makeText(MainActivity.this, "Tools menu selected.", Toast.LENGTH_SHORT).show(); return true; default: return super.onOptionsItemSelected(item); } } }
To enable an options menu in an activity, we need to override the onCreateOptionsMenu()
and the onOptionsItemSelected()
methods.
@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); return true; }
Inside the onCreateOptionsMenu()
method, we build the options menu from the options_menu.xml
file. We use the MenuInflater
class to do the job.
@Override public boolean onOptionsItemSelected(MenuItem item) { ... }
The onOptionsItemSelected()
method handles the click events on the menu items.
case R.id.settings: Toast.makeText(MainActivity.this, "Settings menu selected.", Toast.LENGTH_SHORT).show(); return true;
In case of the selection of the Settings menu item we show a Toast window with "Settings menu selected" message.

Context menu
We have a ListView
with the names of our planets. A long-click on an element will show a context menu with tree options: Delete, Uppercase, and Lowercase.
The manifest file is not modified.
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="fill_parent" android:layout_height="fill_parent" > <ListView android:id="@+id/lvId" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>
This is main.xml
file. It contains a ListView
widget.
strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">ContextMenu</string> <string-array name="planets"> <item>Mercury</item> <item>Venus</item> <item>Earth</item> <item>Mars</item> <item>Jupiter</item> <item>Saturn</item> <item>Uranus</item> <item>Neptune</item> <item>Pluto</item> </string-array> </resources>
This is the strings.xml
resource file.
row.xml
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:textSize="20sp"> </TextView>
This is the row.xml
resource file. Each row of a ListView
consists of a single TextView
.
MainActivity.java
package com.zetcode.conmenu; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; import android.view.View; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.widget.AdapterView.AdapterContextMenuInfo; import java.util.Arrays; import java.util.ArrayList; public class MainActivity extends Activity { private ListView lv; private ArrayAdapter<String> la; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); setupUI(); } public void setupUI() { lv = (ListView) findViewById(R.id.lvId); String[] planets = getResources().getStringArray(R.array.planets); ArrayList<String> lst = new ArrayList<String>(); lst.addAll(Arrays.asList(planets)); la = new ArrayAdapter<String>(this, R.layout.row, lst); lv.setAdapter(la); registerForContextMenu(lv); } @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); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); int pos = info.position; String i = la.getItem(pos); switch (item.getItemId()) { case R.id.delId: la.remove(i); return true; case R.id.upId: String upln = i.toUpperCase(); la.remove(i); la.insert(upln, pos); return true; case R.id.loId: String lpln = i.toLowerCase(); la.remove(i); la.insert(lpln, pos); return true; default: return super.onContextItemSelected(item); } } }
In order to implement the context menu, we have to override the onCreateContextMenu()
and the onContextItemSelected()
methods. We also need to call the registerForContextMenu()
method for a specific view.
String[] planets = getResources().getStringArray(R.array.planets); ArrayList<String> lst = new ArrayList<String>(); lst.addAll(Arrays.asList(planets));
We will be deleting items of the ListView
. Therefore, we need to use an ArrayList
. Otherwise the list would be read-only.
registerForContextMenu(lv);
The context menu is registered for the ListView
widget.
@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 the onCreateContextMenu()
method we build the context menu from the context_menu.xml file.
@Override public boolean onContextItemSelected(MenuItem item) { ... }
The onContextItemSelected()
reacts to list item selection events.
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); int pos = info.position; String i = la.getItem(pos);
To find out more about the selected item, we use the AdapterContextMenuInfo
class. We get the position and the text of the selected item.
case R.id.delId: la.remove(i); return true;
If we select the Delete context menu option, we remove the item from the ArrayAdapter
.
case R.id.upId: String upln = i.toUpperCase(); la.remove(i); la.insert(upln, pos); return true;
For the Uppercase option, we modify the string, remove the original one and insert a new one.

Popup menu
The example shows a PopupMenu
after clicking on a button.
The manifest file is not modified.
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="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/btnId" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginTop="10dip" android:text="@string/btn_label" android:onClick="onClick" /> <TextView android:id="@+id/tvId" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dip" /> </LinearLayout>
This is main.xml
file. We have a Button
widget and a TextView
widget. The button will show a PopupMenu
.
strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">PopupMenu</string> <string name="btn_label">Show menu</string> <string name="pm1">Item 1</string> <string name="pm2">Item 2</string> </resources>
This is the strings.xml
resource file.
popup_menu.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/settings" android:title="@string/pm1" /> <item android:id="@+id/tools" android:title="@string/pm2" /> </menu>
This is popup_menu.xml
file. It defines two menu items. The file is located in the res/menu/
subdirectory.
MainActivity.java
package com.zetcode.popmenu; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.MenuItem; import android.widget.TextView; import android.widget.PopupMenu; import android.widget.PopupMenu.OnMenuItemClickListener; public class MainActivity extends Activity implements OnMenuItemClickListener { private TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv = (TextView) findViewById(R.id.tvId); } public void onClick(View v) { showPopupMenu(v); } public void showPopupMenu(View v) { PopupMenu pm = new PopupMenu(MainActivity.this, v); pm.getMenuInflater().inflate(R.menu.popup_menu, pm.getMenu()); pm.setOnMenuItemClickListener(this); pm.show(); } @Override public boolean onMenuItemClick(MenuItem item) { tv.setText(item.toString() + " selected"); return true; } }
A PopupMenu
is displayed after clicking on the button widget.
public void onClick(View v) { showPopupMenu(v); }
This method is a callback to the button click. The relation is set in the main.xml
file via an attribute. The method calls the showPopupMenu()
method.
public void showPopupMenu(View v) { PopupMenu pm = new PopupMenu(MainActivity.this, v); pm.getMenuInflater().inflate(R.menu.popup_menu, pm.getMenu()); pm.setOnMenuItemClickListener(this); pm.show(); }
We create an instance of the PopupMenu
class. It builds the menu, sets the OnMenuItemClickListener
and shows the PopupMenu
.
@Override public boolean onMenuItemClick(MenuItem item) { tv.setText(item.toString() + " selected"); return true; }
After selecting a menu item the onMenuItemClick()
method is called. It sets the item's title to the TextView
widget.
In this chapter of the Android development tutorial, we have worked with menus.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论