How to handle onContextItemSelected in a multi fragment activity?

前端 未结 11 2079
天命终不由人
天命终不由人 2020-11-29 17:26

I\'m currently trying to adapt my application to use the \"Compatibility Libraries for Android v4\" to provide the benefits of the usage of fragments even to Android 1.6 use

11条回答
  •  温柔的废话
    2020-11-29 18:04

    I'll post an answer even though you found a workaround because I just dealt with a similar issue. When you inflate the context menu for a specific fragment, assign each menu item a groupId that is unique to the fragment. Then test for the groupId in 'onContextItemSelected.' For Example:

    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
        menu.add(UNIQUE_FRAGMENT_GROUP_ID, MENU_OPTION_1, 0, R.string.src1);
        menu.add(UNIQUE_FRAGMENT_GROUP_ID, MENU_OPTION_2, 0, R.string.src2);
    }
    public boolean onContextItemSelected(MenuItem item) {
        //only this fragment's context menus have group ID of -1
        if (item.getGroupId() == UNIQUE_FRAGMENT_GROUP_ID) {
            switch(item.getItemId()) {
            case MENU_OPTION_1: doSomething(); break;
            case MENU_OPTION_2: doSomethingElse(); break;
        }
    }
    

    This way all of your fragments will still receive calls to 'onContextItemSelected,' but only the correct one will respond, thus avoiding the need to write activity-level code. I assume a modified version of this technique could work even though you aren't using 'menu.add(...)'

提交回复
热议问题