Android上下文菜单项出现两次(BUG)

时间:2012-10-02 14:32:32

标签: android contextmenu

我以同样的方式完成代码我总是这样做&不知道我错在哪里:

@Override
public void onCreate(){
   ...
   this.registerForContextMenu(lv);

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
   super.onCreateContextMenu(menu, v, menuInfo);
   MenuInflater inflater = getMenuInflater();
   inflater.inflate(R.menu.context_menu_device_item_remove, menu);
}

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
     <item android:id="@+id/context_menu_item_remove_id"
           android:title="Remove" />
     <item android:id="@+id/context_menu_item_clear_all_id"
           android:title="Clear all" />
</menu>

正如你所看到的那样..效果是:

enter image description here

由于使用了AdapterContextMenuInfo.position,应用程序在点击第三个或第四个元素时崩溃:

@Override
public boolean onContextItemSelected(MenuItem item) {
     AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
     System.out.println("## info.position: "+info.position);
...

你见过这个吗? &安培;你是怎么逃过来的?

2 个答案:

答案 0 :(得分:0)

尝试以下代码:

     public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {

    menu.add(0, MENU_ITEM_SEND_MSG, 0, "Send a Message");
    menu.add(0, MENU_ITEM_MAKE_A_CALL, 0, "Make a Call");

}


     public boolean onContextItemSelected(MenuItem item) {

    SharedPreferences server_sp = getApplicationContext()
            .getSharedPreferences("server", MODE_PRIVATE);
    String server = server_sp.getString("Server", "server");

    switch (item.getItemId()) {
    case MENU_ITEM_SEND_MSG:
           //do ur stuff

    case MENU_ITEM_MAKE_A_CALL:

        //do ur stufff
        break;
    }
    return false;
}

答案 1 :(得分:0)

显然BUG是由于有this.registerForContextMenu(lv);(晚餐课程中的第一个)的2次调用..所以是的,我的坏。