首先在res/menu下创建上下文菜单context_menu.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/file_context_menu_rename" android:title="重命名"/> <item android:id="@+id/file_context_menu_copy" android:title="复制"/> <item android:id="@+id/file_context_menu_detail" android:title="详情"/> </menu>
然后在Activity里注册listView的上下文菜单.
listView.setOnCreateContextMenuListener(this);
下面是上下文菜单的创建和响应.
/** * 创建上下文菜单 */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { getMenuInflater().inflate(R.menu.schedule_context_menu, menu); super.onCreateContextMenu(menu, v, menuInfo); } /** * 上下文菜单监听 */ @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); // info包含了上下文菜单每一项的信息,比如info.position是上下文菜单项的位置 switch (item.getItemId()) { case R.id.file_context_menu_rename: // do something return true; case R.id.file_context_menu_copy: // do something return true; case R.id.file_context_menu_move: // do something return true; default: break; } return super.onContextItemSelected(item); }