-1

我在一个活动中有两个列表视图,我想使用 ContextMenu 从其中一个中删除项目。我想使用相同的上下文菜单,可以吗?我在看这里,但所有答案都指向两个不同的上下文菜单。谢谢!!!

这是我的代码:

    //Register both ListViews
    Listview1= (ListView)findViewById(R.id.PedlstItens) ;
    Listview1.setOnCreateContextMenuListener(this);
    registerForContextMenu(Listview1);

    Listview2 = (ListView)findViewById(R.id.PedlstCartao) ;
    Listview2.setOnCreateContextMenuListener(this);
    registerForContextMenu(Listview2);

之后,膨胀菜单:

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

然后 ContextMenu 行为...我不知道如何指向正确的 Listview 以删除该项目:

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

        ***//THIS IS WHERE I DONT KNOW WHAT TO DO***
    switch (item.getItemId()) {
        case R.id.remove_item:
            Listview1.remove(info.position);
            Listview1array.notifyDataSetChanged();
        return true;
    }
    return false;
}
4

1 回答 1

0

找到了解决方案:

在“onCreateContextMenu”中,我将列表的 ID 存储在变量 ListToRemove 中:

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        ListToRemove = v.getId(); //Here i store in which listview my ContextMenu was created
        inflater.inflate(R.layout.menu_remove, menu);
    }

然后,在“onContextItemSelected”中,我做了一个开关来控制行为。***注意:我的 ContextMenu 只有 1 项,所以我从原始代码中删除了“getItemId()”。

public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    boolean retorno = false;

    switch (ListToRemove ) { 
    case R.id.ListView1:
        {
             ListView1.remove(info.position);
         ListView1Array.notifyDataSetChanged();
         retorno = true;
             break;
        }
    case R.id.ListView2:
        {
             ListView2.remove(info.position);
             ListView2Array.notifyDataSetChanged();
             retorno = true;
             break;
        }
    }
    return retorno;
}

效果很好!!!

于 2013-08-25T06:14:29.647 回答