MY mENU


Tuesday 13 March 2012

Context Menu in Android

Context Menu: Context menus are the menus that appear when you right-click in windows. In android Context menu are attached to widgets and the appear when you click on the widget for a long time (long click). The Context Menu is a floating list of menu items that appears when a user touches and holds a particular item displayed in the view, which has a menu associated with it.

To add context menus to widgets you have to do two things:

  1. Register the widget for a context menu.
  2. Add menu items to the context menu.

So to register a context menu with a TextView you do it like this:

1@Override
2    public void onCreate(Bundle savedInstanceState) {
3        super.onCreate(savedInstanceState);
4        setContentView(R.layout.main);
5        txt1=(TextView)findViewById(R.id.txt1);
6        registerForContextMenu(txt1);
7    }

We call registerForContextMenu(View V) method to tell the activity that the view is going to have a context menu. Then we add items to the context menu by overriding the onCreateContext method:

1@Override
2    public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo info)
3    {
4     menu.setHeaderTitle("Context Menu");
5     menu.add("Item");
6    }
When you make a long click on the text view the context menu will appear like this:



The onCreateContextMenu method has the following parameters:

  1. Context Menu: an instance of the context menu.
  2. View: the view to which the context menu is attached.
  3. ContextMenuInfo: carries additional information regarding the creation of the context menu.

To handle the context menu items click events you can implement the callback method onContextItemSelected.  We do it the same way we handle onOptionsItemSelected.

1@Override
2    public boolean onContextItemSelected(MenuItem item)
3    {
4     txt.setText(item.getTitle());
5     return true;
6    }

No comments:

Post a Comment