androidandroid-fragmentsandroid-contextmenu

Problems with onContextItemSelected with two fragments


I am using a ViewPager. I have two tabs and, consequently, two fragments that each one have their own Context Menu Options. My problem is when I click in Context Menu options in Fragment B, the method onContextItemSelected() in fragment A is called. How can I solve this?

I do the same as shown in the official Android documentation: https://developer.android.com/guide/topics/ui/menus.html#context-menu

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

    PositionClicked = info.position;

    switch (item.getItemId()) {

        case R.id.menu_edit:
            return true;

        case R.id.menu_archive:
            return true;

        case R.id.menu_report:
            return true;

        case R.id.menu_delete:
            Log.i(TAG, "Delete Menu Buttom");

            new AlertDialog.Builder(getActivity()).setTitle("Tem certeza?")
                .setMessage("Você está prestes a deletar sua Postagem!")
                .setPositiveButton("Deletar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        //ShowSwipeRefreshin();

                        delete_item(MongodbObjtoDelete);

                        DialogResp = true;
                        feedItems.remove(PositionClicked);
                        listAdapter.notifyDataSetChanged();
                    }
                }).setNegativeButton("Cancelar", null).show();

            return true;

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

Solution

  • you can fix it like this :

    FragmentManager manager = getFragmentManager();
    if (manager.findFragmentByTag("frag1").isVisible()){
        // do fragment 1
    }else{
    
    }