ListView:長按彈出上下文選單(ContextMenu)
阿新 • • 發佈:2019-02-03
有兩種方法實現長按彈出上下文選單:
方法一:
1)註冊上下文選單
/** * 上下文選單演示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"); } }
2)生成上下文選單
在activity中重新onCreateContextMenu()方法
@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, "刪除"); }
3)響應上下文選單項
@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; }
方法二、
1)設定上下文選單監聽
@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);
}
2)定義上下文選單監聽器
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); } };
3)響應上下文選單項
@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);
}