使用相同的菜单从不同的列表中删除项目

时间:2013-08-12 18:56:27

标签: java android eclipse listview contextmenu

我在一个活动中有两个listview,我想使用ContextMenu从其中一个中删除itens。我想使用相同的上下文菜单,这可能吗?我在这里看,但所有答案都指向两个不同的上下文菜单。感谢!!!

这是我的代码:

    //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;
}

1 个答案:

答案 0 :(得分: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;
}

工作得很好!!!