2009-01-11 80 views

回答

73

在onCreate方法調用registerForContextMenu這樣的:

registerForContextMenu(getListView()); 

,然後填充上onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo)菜單。該menuInfo參數可以提供關於該項目是長期的點擊這樣的信息:

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

,你通常的方式調用menu.add添加菜單項:

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

當用戶拿起一個選項,onContextItemSelected被調用。同樣onMenuItemSelected,這個事實在文檔中沒有明確解釋,除了說你使用其他方法接收來自上下文菜單的調用;請注意,不要共享ID。

在onContextItemSelected你可以得到阿霍德的MenuInfo的,因此通過調用getMenuInfo()選擇的項目的ID:

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

啊,謝謝。一直在網上尋找,但只能找到舊版本。這個與蛋糕完美搭配。 – 2009-04-23 11:51:12

5
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; 
} 
相關問題