簡體   English   中英

從ContextMenu獲取ExpandableListView的選定項

[英]Getting ExpandableListView's selected item from ContextMenu

嗨,我從ContextMenu獲取ExpandableListView的項目ID時遇到問題,我需要從數據庫中刪除該條目(即使用內容提供程序)。

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    menu.add(Menu.NONE, MENU_EDIT, Menu.NONE, "Edit");
    menu.add(Menu.NONE, MENU_REMOVE, Menu.NONE, "Remove");
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuItem.getMenuInfo();
    switch (item.getItemId()) {
        case MENU_EDIT:
            editEntry(info.id);
            return true;
        case MENU_REMOVE:
            deleteEntry(info.id);
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}

private void deleteEntry(long id) {
    Uri uri = Uri.parse(DatabaseManager.CONTENT_URI + "/" + id);
    getActivity().getContentResolver().delete(uri, null, null);
}

顯示了ContextMenu,但是當我單擊“刪除”時,沒有任何反應。 你能告訴我怎么辦嗎?

由於ExpandableListView具有兩個級別-組和子級-很難直接解釋“ ID”。

您需要將ExpandableListContextMenuInfo中的信息分解為組位置和子位置。

使用這兩個值,您就可以從用作ExpandableListView的數據源的適配器(這里為this.exandableListAdapter )中檢索選定的項目。 適配器的getChild()返回的對象可以轉換為最初放入適配器的任何(自定義)類型:

ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuItem.getMenuInfo();
int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
MyItemClass item =(MyItemClass) this.expandableListAdapter.getChild(groupPos, childPos);

通過此項目,您應該可以輕松地在數據庫中獲取ID或所需的任何特定信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM