Friday, August 5, 2011

Context Menu:


Context Menu is a floatinglist of menu items that appears when the user touches and holds a view that's registered to provide a context menu. It's conceptually similar to the menu displayed when the user performs a "right-click" on a PC, which provides the user access to actions that pertain to a specific item in the user interface. On Android, a context menu is displayed when the user performs a "long press" (press and hold) on an item. It could created for any views.


To create a context menu, you should:
  1. Have the view you need to attach the context menu, and registered these views by call registerForContextMenu();
    E.g. registerForContextMenu(findViewById(R.id.ac_selectContact));
           registerForContextMenu(getListView());
  2. Define the appearance of the context menu;
    Override the function onCreateContextMenu().
    There two ways to create the context menu by using this function:
    • Using predefined menu xml file;
      @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);
      }
       Here the R.menu.context_menu is the menu information you need to create the menu.
    • Dynamically create menu, and add items to the menu;
      @Override
      public void onCreateContextMenu(ContextMenu menu, View v,
                                      ContextMenuInfo menuInfo) {
        menu.setHeaderIcon(R.drawable.header); 
        if(v == findViewById(R.id.ac_selectContact)){ menu.add(0, Menu1, 0. R.string.mi1) ...}
        else if(v == findViewById(R.id.photo)){...}
      
      }
  3. Define the behavior of the context menu
    Override the function onContextItemSelected().
    @Override
    public boolean onContextItemSelected(MenuItem item) {
      AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
      switch (item.getItemId()) {
      case R.id.edit:
        editNote(info.id);
        return true;
      case R.id.delete:
        deleteNote(info.id);
        return true;
      default:
        return super.onContextItemSelected(item);
      }
    }

No comments :

Post a Comment