什么是"上下文菜单"和方法registerForContextMenu()

Lee*_*fin 17 android android-widget android-emulator android-intent android-layout

Activity类中,有一个方法叫做registerForContextMenu(View view).

该机器人文档说明,该方法用于注册一个上下文菜单中显示用于给定视图(多个视图可以显示上下文菜单).

  • " 上下文菜单 "是什么意思?这是指物理菜单按钮还是什么?
  • 我还需要对该方法进行一些解释registerForContextMenu(View view),我不清楚只是在线阅读该文档.

Chr*_*ris 11

它基本上是一个弹出菜单,当您长按某些UI元素(通常是ListView中的项目)时会显示该菜单.

您应该查看开发者指南的菜单部分.


小智 7

这是来自Android开发者:菜单-Android开发人员

上下文菜单是当用户对元素执行长按时显示的浮动菜单.它提供影响所选内容或上下文框架的操作.

想象一下,你想在listview中使用conext菜单

//Constants for context menu options
public static final int MENU_MARK = 1;
public static final int MENU_REMOVE = 2;

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    ...
    ...
    // Specify that your listview has a context menu attached
    registerForContextMenu(getListView());
}

// here you create the context menu
@Override
public void onCreateContextMenu(ContextMenu menu, View v, 
   ContextMenuInfo menuInfo) {
  menu.add(Menu.NONE, MENU_MARK, Menu.NONE, "MARK");
  menu.add(Menu.NONE, MENU_REMOVE, Menu.NONE, "Remove");
}

// This is executed when the user selects an option
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
    case MENU_MARK:
        mark_item(info.id);
        return true;
    case MENU_REMOVE:
        delete_item(info.id);
        return true;
    default:
        return super.onContextItemSelected(item);
   }
}
Run Code Online (Sandbox Code Playgroud)