如何从中选择上下文菜单选项的视图?

时间:2014-12-04 12:27:29

标签: java android menu contextmenu

在我的应用中,我动态创建了一些视图,所有视图都注册了相同的上下文菜单。

for(int j = 0; j < CELLS_IN_ROW; j++) {
    MyView v = new MyView();
    ((Activity) context).registerForContextMenu(v);
}
/* ----------------------------------------------- */


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.cell_context_menu, menu);
}

    @Override
    public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.myOption:
            MyView viewClicked = ?????

            doSomethingDependingOnView(viewClicked);
            return true;

        default:
            return super.onContextItemSelected(item);
    }
}

但是当单击菜单选项时,我想根据单击的视图打开上下文菜单进行不同的操作。我怎么能这样做?

3 个答案:

答案 0 :(得分:1)

当您的onCreateContextMenu启动时,由于其参数 view ,您可以在clickedView上找到参考。

onCreateContextMenu(ContextMenu cM,查看 视图 ,ContextMenuInfo cMI)

所以你必须在你的Activity(或Fragment)中声明一些View变量, 那么你应该在onCreateContextMenu中初始化那个,最后你可以在onContextItemSelected中使用它

MyView viewClicked;

@Override
public void onCreateContextMenu(ContextMenu menu, 
                           View view, // this is your clicked view
                           ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);

MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.cell_context_menu, menu);
viewClicked = view; // <---!!!

}

@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
    case R.id.myOption:

        viewClicked.someMethod();

        doSomethingDependingOnView(viewClicked);
        return true;
    default:
        return super.onContextItemSelected(item);
}

}

答案 1 :(得分:0)

试试这个:

@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
    case R.id.myOption:

        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        MyView viewClicked = (MyView) info.targetView;      

        doSomethingDependingOnView(viewClicked);
        return true;

    default:
        return super.onContextItemSelected(item);
}

答案 2 :(得分:0)

不是最好的方法,而是唯一似乎有效的方法:

// create a global variable
Button clickedButton = null;

// save the button
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    clickedButton = (Button) v;
}

// do something with the clickedButton
@Override
public boolean onContextItemSelected(MenuItem item) {
    doSomethingDependingOnView(clickedButton);
    return true;
}