借助于link1link2,我为我的两个列表视图创建了一个ContextMenu,如下所示

    final int DELETE = 0;
    final int CANCEL = 1;
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
    super.onCreateContextMenu(menu, v, menuInfo);
    switch(v.getId()){
    case R.id.history_listView:
        menu.setHeaderTitle("Delete History?");
        menu.add(0, DELETE, 0, "Delete");
        menu.add(0, CANCEL, 0, "Cancel");
        break;

    case R.id.bookmark_listView:
        menu.setHeaderTitle("Delete Bookmark?");
        menu.add(0, DELETE, 0, "Delete");
        menu.add(0, CANCEL, 0, "Cancel");
    }
}


现在,我想拥有两个onContextItemSelected方法,一个用于历史记录,另一个用于书签。我为历史创建了一个,运行正常。

@Override
public boolean onContextItemSelected(MenuItem item){
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

    switch(item.getItemId()){
    case DELETE:
        String deleteSelectedHistory = (String) historyData.get(info.position);
        historyData.remove(info.position);
        historyAdapter.notifyDataSetChanged();

        break;

    case CANCEL:
        break;
    }
    return false;
}


但是无法为书签创建另一个。是否可以在同一活动中使用另一个onContextItemSelected方法?还是有办法创建第二个?

最佳答案

请检查此代码。它可能会帮助您。

final int HIS_DELETE = 0;
final int HIS_CANCEL = 1;
final int BM_DELETE = 2;
final int BM_CANCEL = 3;

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    switch (v.getId()) {
    case R.id.history_listView:
        menu.setHeaderTitle("Delete History?");
        menu.add(0, HIS_DELETE, 0, "Delete");
        menu.add(0, HIS_CANCEL, 0, "Cancel");
        break;

    case R.id.bookmark_listView:
        menu.setHeaderTitle("Delete Bookmark?");
        menu.add(0, BM_DELETE, 0, "Delete");
        menu.add(0, BM_CANCEL, 0, "Cancel");
    }
}


和onContextItemSelected方法,例如,

    @Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
            .getMenuInfo();

    switch (item.getItemId()) {
    case HIS_DELETE:
        Log.d("System out", "HIS_DELETE");
        break;
    case HIS_CANCEL:
        Log.d("System out", "HIS_CANCEL");
        break;
    case BM_DELETE:
        Log.d("System out", "BM_DELETE");
        break;
    case BM_CANCEL:
        Log.d("System out", "BM_CANCEL");
        break;
    }
    return false;
}

07-24 09:46
查看更多