传递按钮触发ContextMenu

时间:2012-02-27 23:43:19

标签: android

所以我是Android新编程和学习的新手。我目前正在开发一种音板,允许用户将声音设置为铃声或通知。我已经成功设置了上下文菜单,并且能够区分用户在上下文菜单中单击的内容。我唯一的问题是我无法弄清楚如何判断哪个按钮触发了上下文菜单。有人可以帮忙吗?

由于 贾斯汀

编辑:我找到了解决方案。我是这样做的:

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

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

        switch (item.getItemId()) {
            case R.id.Ringtone:
                if(lastButton == SoundButton)
                Toast.makeText(getApplicationContext(), "Ringtone soundbutton selected", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.Notification:
                if(lastButton == SoundButtonButton){
                    Toast.makeText(getApplicationContext(), "Notification soundbutton set", Toast.LENGTH_SHORT).show();
                }

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

1 个答案:

答案 0 :(得分:1)

一种方法是在注册上下文菜单之前为视图设置id。如果您使用的是按钮:

    Button button = ...;
    button.setId(some_id);

    Button button2 = ...;
    button2.setId(some_id_2);
    ...

    registerForContextMenu(b);  

    public boolean onContextItemSelected(MenuItem item)
    {
        int id = item.getItemId();

        if (id == some_id)
            ...
        else if (id == some_id_2)
            ...
    }