Learn about context menus and long-press user interaction on Android in this Android SDK quick tip!
The Android platform provides a few standard menus you can use in your apps. The context menu appears when users long-press user interface items, pressing the item and holding it until the menu appears. Android users are typically accustomed to this type of interaction, as it is standard for system functions such as altering home screen icons. The Android developer guide compares the context menu to right-clicking on a computer. Implementing the context menu is straightforward, and is a key ingredient in many applications.
Step 1: Open or Create a Project
If you have an existing app you want to implement a context menu with, open the Activity class you want to add it to. Otherwise, create a new project and add an Activity class to it. The source code includes all necessary processing so if you're unsure, refer to that. If you are creating a new Activity to your application, remember to add it to your Manifest file as follows:
<activity android:name=".MyLovelyClass"></activity>
Alter the name to suit your own class.
Step 2: Import the Android Resources
Add the import statements necessary for the context menu processing. You may not need all of these imported resources depending on how you choose to implement the context menu, and your IDE may add some of them automatically. To use the technique as demonstrated in this tutorial, your Activity class will need the following imports:
import android.app.Activity; import android.os.Bundle; import android.view.ContextMenu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.widget.TextView; import android.widget.Toast;
Step 3: Add a UI Element to Long-Press
Within the layout for your Activity, include the user interface view element you want users to be able to long-press for the context menu. The following sample layout XML content demonstrates how to do this, so use it if you're building a new project and could use some help:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:gravity="center" > <TextView android:id="@+id/press" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30sp" android:text="Long-press me" /> </LinearLayout>
You can instruct your Activity class to use this layout as follows:
public class MyLovelyClass extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.lovely_layout); } }
Alter the name to suit your own class. In this case, the XML layout file is saved as "lovely_layout.xml" in the application's "res/layout" folder.
Step 4: Create a Menu Resource
If your application package does not have a "menu" folder inside the "res" resources directory, create one. Inside the menu folder, create a new XML file for your menu and save it with a name of your choosing. In this file, you define the items that will appear in the context menu. You can use the following code:
<menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/option1" android:title="A Context Option" /> <item android:id="@+id/option2" android:title="Another Context Option" /> </menu>
Alter the items to suit your own app and add more if you need to.
Step 5: Register for the Context Menu
You need to instruct Android to listen for long-presses on the user interface item you want to provide the context menu for. Inside your Activity's "onCreate" method, add the following code, making alterations to suit the details of your own app:
//get a reference to the view for pressing TextView pressView = (TextView)findViewById(R.id.press); //register if for context registerForContextMenu(pressView);
Specify the ID attribute you used for your own view element in the XML layout file where this example uses "press". This instructs your app to detect users long-pressing the view item specified. When that happens, the app will call the "onCreateContextMenu" method in which you can instruct it to use your context menu resource.
Step 6: Use Your Menu Resource
You need to let Android know you want it to use the XML menu resource you created as the context menu for the view item registered. Add the following method in your Activity class:
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.lovely_context, menu); }
Alter this if necessary to reflect the file-name you chose for your own context menu XML file. This example uses a menu file named "lovely_context.xml" for demonstration.
Step 7: Implement Long-Presses
Your Activity class now detects long-presses on your view item, but you still need to define what should happen when each item in your menu is selected. Add the following method to your class:
public boolean onContextItemSelected(MenuItem item) { //find out which menu item was pressed switch (item.getItemId()) { case R.id.option1: doOptionOne(); return true; case R.id.option2: doOptionTwo(); return true; default: return false; } }
Alter the case statements to reflect the ID attributes you gave your menu items in the XML file. The switch statement uses the passed menu item parameter to check which menu option the user has selected. You can include an additional case statement for each option in your context menu if you added more yourself. Within each statement, the code specifies a method to call when the user chooses that item. You now need to implement the methods specified in this statement.
Step 8: Add Context Option Methods
Defining dedicated methods for each context menu option keeps your Activity class well organized, so add each one you included in your switch statement. The following sample methods demonstrate the principle:
//method to execute when option one is chosen private void doOptionOne() { Toast.makeText(this, "Option One Chosen...", Toast.LENGTH_LONG).show(); } //method to execute when option two is chosen private void doOptionTwo() { Toast.makeText(this, "Option Two Chosen...", Toast.LENGTH_LONG).show(); }
These methods simply write a short message to the interface for demonstration. In your own classes you can implement whatever processing you need.
Conclusion
Your app now has the processing code necessary to provide the context menu on users pressing and holding your chosen view item. The complete Activity code follows, and you can download the attached source folder which also contains the XML files for the layout and menu items.
import android.app.Activity; import android.os.Bundle; import android.view.ContextMenu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.widget.TextView; import android.widget.Toast; public class MyLovelyClass extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.lovely_layout); //get a reference to the view for pressing TextView pressView = (TextView)findViewById(R.id.press); //register it for context registerForContextMenu(pressView); } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.lovely_context, menu); } public boolean onContextItemSelected(MenuItem item) { //find out which menu item was pressed switch (item.getItemId()) { case R.id.option1: doOptionOne(); return true; case R.id.option2: doOptionTwo(); return true; default: return false; } } private void doOptionOne() { Toast.makeText(this, "Option One Chosen...", Toast.LENGTH_LONG).show(); } private void doOptionTwo() { Toast.makeText(this, "Option Two Chosen...", Toast.LENGTH_LONG).show(); } }
If your application includes a help section or instructions of any kind, you may wish to mention the item with the context menu, as your users may not realise that this functionality has been provided.
About the Author
Sue Smith
I'm a Web / software developer and technical / comedy writer - see BeNormal.info for details. The Nonsense apps are my first attempt at Android development. I've written for lots of different clients, including Smashing Magazine. My own sites include BrainDeadAir spoof arts magazine. Follow me on Twitter @BrainDeadAir or e-mail me at [email protected].
Comments