任何视图的Android上下文菜单

时间:2016-12-11 08:36:41

标签: android android-activity android-menu android-contextmenu

据我所知,Context Menu不仅可以为ListView注册任何视图。今天我正在尝试为Custom ImageView注册上下文菜单。像这样:

// In onCreateView() method of activity
registerForContextMenu(mViewHolder.profileImageView);

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    switch (v.getId()) {
        case R.id.profile_imageview:
            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
            menu.add(Menu.NONE, CONTEXT_MENU_ITEM_CHANGE_PICTURE, 0, "Change Picture");
    }
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
    switch (item.getItemId()) {
        case CONTEXT_MENU_ITEM_CHANGE_PICTURE:
            //Toast.makeText(mParentActivity, "Delete " + info.position + "th item", Toast.LENGTH_LONG).show()
            Toast.makeText(this, "Go to library", Toast.LENGTH_SHORT).show();
            return true;
        default:
            return true;
    }
}

我没有找到任何没有ListView注册上下文菜单的例子。有人会给我一个例子或者可以弄清楚我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

你需要写super.onCreateContextMenu(menu, v, menuInfo); 毕竟代码如下:

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

    switch (v.getId()) {
        case R.id.profile_imageview:
            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
            menu.add(Menu.NONE, CONTEXT_MENU_ITEM_CHANGE_PICTURE, 0, "Change Picture");
            super.onCreateContextMenu(menu, v, menuInfo);

    }
}