RSS

How to add a context menu in Android

23 Jan
  1. Create an Android XML file of Menu type
  2. Add menu options as you preferred. Each menu option should be indicated as <item> XML element.
  3. This is my context_menu.xml file.
    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/item1"   android:title="option1"></item>
    <item android:id="@+id/item2"   android:title="option2"></item>
    </menu>
    
  4. Override onCreateContextMenu and onContextItemSelected in your Activity.java file
    Add a button in main.xml to respond our context menu.

    package com.my.option;
    
    import java.util.zip.Inflater;
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.ContextMenu;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ContextMenu.ContextMenuInfo;
    import android.widget.Button;
    
    public class ContextMenuActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    Button b = (Button) findViewById(R.id.button1);
    registerForContextMenu(b);
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
    ContextMenuInfo menuInfo) {
    
    MenuInflater inflator = getMenuInflater();
    inflator.inflate(R.menu.context_menu, menu);
    
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    if(item.getItemId() == R.id.item1)
    Log.d("Edit", "Selected : Edit Option");
    if(item.getItemId() == R.id.item2)
    Log.d("Delete", "Selected : Delete Option");
    return super.onContextItemSelected(item);
    }
    }
    
Advertisements
 
Leave a comment

Posted by on January 23, 2012 in Android

 

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: