0

我有一个列表视图。我实现了 OnItemClickListener 以在单击项目时打开 ContextMenu。

lv = getListView();
    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            showMenu(view);
        }
    });

以及创建菜单的代码。

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

public void showMenu(View v) {
    registerForContextMenu(v);
    openContextMenu(v);
}

我的问题是,当我单击 ListView 的一项时,它确实打开了菜单。但是如果我回到 ListView,我就不能再点击那个项目了。其他项目同理,关闭菜单后无法点击。谁能帮我这个?

4

2 回答 2

2

你设置不正确。设置适配器时注册上下文菜单,而不是单击按钮。

它应该如下所示:

setListAdapter(lists);
registerForContextMenu(getListView());

然后你有你的onCreateContextMenuonContextItemSelected方法(我以编程方式创建我的,但你的膨胀的方法也一样):

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("List Operations");
    menu.add(0, v.getId(), 0, "Edit List");
    menu.add(0, v.getId(), 0, "Delete List");
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
            .getMenuInfo();
    if (item.getTitle() == "Edit List") {
      //  Do your edit stuff here
    } else if (item.getTitle() == "Delete List") {
      // Do your delete stuff here
    }
    return super.onContextItemSelected(item);
}

onItemClick除非您想在短按项目上做某事(上下文菜单是长按),否则您不需要使用。

于 2012-06-07T06:35:10.743 回答
0

The following code will works.

code:

  ListView listview=(ListView)findViewByid(R.id.listview);

   /**** here write appending data to listview*******/
     ArrayAdapter<String> adp=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,/**your list items**/);
     listview.setadapter(adp);
     registerForContextMenu(listview);

   //listview item click listener
  listview.setOnItemClickListener(new OnItemClickListener(){

@Override
public void onItemClick(AdapterView<?> arg0, View v, int p, long arg3) {
    // TODO Auto-generated method stub

 Toast.makeText(getApplicationContext(), "selected" + p, 30).show();
}});

   /****do your context menu code here*******/
于 2012-06-07T06:39:16.177 回答