How do you implement context menu in a ListActivity on Android?

浪子不回头ぞ 提交于 2019-11-26 17:57:20

问题


How do you implement a context menu triggered by a long click or tap on a ListActivity that is using the built in layouts and a ListAdapter?


回答1:


On the onCreate method call registerForContextMenu like this:

registerForContextMenu(getListView());

and then populate the menu on onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo). The menuInfo argument can provide information about which item was long-clicked in this way:

AdapterView.AdapterContextMenuInfo info;
try {
    info = (AdapterView.AdapterContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
    Log.e(TAG, "bad menuInfo", e);
    return;
}
long id = getListAdapter().getItemId(info.position);

and you add menu items in the usual way calling menu.add:

menu.add(0, MENU_ITEM_ID, 0, R.string.menu_string);

and when the user picks an option, onContextItemSelected is called. Also onMenuItemSelected and this fact is not explicitly explained in the documentation except to say that you use the other method to receive the calls from the context menu; just be aware, don't share ids.

On onContextItemSelected you can get ahold of the MenuInfo and thus the id of the item selected by calling getMenuInfo():

try {
    info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
    Log.e(TAG, "bad menuInfo", e);
    return false;
}
long id = getListAdapter().getItemId(info.position);



回答2:


You should also look at Activity.registerForContextMenu(View).




回答3:


listView = (ListView) findViewById(R.id.listpockets);
registerForContextMenu(listView);



public void onCreateContextMenu(android.view.ContextMenu menu, View v, android.view.ContextMenu.ContextMenuInfo menuInfo) {
    //AdapterContextMenuInfo info = (AdapterContextMenuInfo)menuInfo;
    menu.setHeaderTitle(getString(R.string.titleDelete));   
    menu.add(0, CommonUtil.CONTEXT_MENU__DELETE_ID, 0, getString(R.string.menuDelete));
};
@Override
public boolean onContextItemSelected(MenuItem item) {

    if(item.getItemId() == CommonUtil.CONTEXT_MENU__DELETE_ID)
    {
       AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
       long id = this.listView.getItemIdAtPosition(info.position);
       Log.d(TAG, "Item ID at POSITION:"+id);
    }
    else
    {
        return false;
    }
    return true;
}


来源:https://stackoverflow.com/questions/433761/how-do-you-implement-context-menu-in-a-listactivity-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!