有两种方法实现长按弹出上下文菜单:
方法一:
/** * 上下文菜单演示Demo * * @author CodingMyWorld 2011-8-27 下午03:22:39 */ publicclass SampleContextMenuActivity extends ListActivity { privatestaticfinal String TAG ="SampleContextMenuActivity"; @Override protectedvoid onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 显示列表 simpleShowList(); // 为所有列表项注册上下文菜单 this.registerForContextMenu(getListView()); } privatevoid simpleShowList() { // list item String[] files =new String[] { "文件1", "文件2", "文件3", "文件4" }; // simple array adapter ArrayAdapter<String> adapter =new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, files); // set adapter this.setListAdapter(adapter); Log.v(TAG, "show simple list"); } }
@Override publicvoid onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { Log.v(TAG, "populate context menu"); // set context menu title menu.setHeaderTitle("文件操作"); // add context menu item menu.add(0, 1, Menu.NONE, "发送"); menu.add(0, 2, Menu.NONE, "标记为重要"); menu.add(0, 3, Menu.NONE, "重命名"); menu.add(0, 4, Menu.NONE, "删除"); }
@Override publicboolean onContextItemSelected(MenuItem item) { // 得到当前被选中的item信息 AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo(); Log.v(TAG, "context item seleted ID="+ menuInfo.id); switch(item.getItemId()) { case1: // do something break; case2: // do something break; case3: // do something break; case4: // do something break; default: returnsuper.onContextItemSelected(item); } returntrue; }
方法二、
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.timing_sms_list_screen); mTimingListView = getListView(); mEmptyView = (LinearLayout)findViewById(R.id.timing_empty_view); // mTimingListView.setEmptyView(mEmptyView); doQuery(); mTimingListView.setOnCreateContextMenuListener(mConvListOnCreateContextMenuListener); }
private final OnCreateContextMenuListener mConvListOnCreateContextMenuListener = new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { Toast.makeText(getApplicationContext(), "onCreateContextMenu()", 1000).show(); menu.add(0, MENU_DELETE, 0, R.string.ti_delete); menu.add(0, MENU_EDIT, 1, R.string.ti_edit); menu.add(0, MENU_SEND_IMMEDIATE, 2, R.string.ti_send_immediately); } };
@Override public boolean onContextItemSelected(MenuItem item) { TimingSmsDataService service = new TimingSmsDataService(getApplicationContext()); switch (item.getItemId()) { case MENU_DELETE: AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo(); Toast.makeText(getApplicationContext(), "id: "+info.id, 1500).show(); // service.deleteTimingSmsById(info.id); break; } return super.onContextItemSelected(item); }