Working with OptionsMenu in nested fragment not updating

吃可爱长大的小学妹 提交于 2019-12-25 09:18:53

问题


I displayed a fragment A that implements a ViewPager with several fragments (nested fragments).

In my nested fragments, I inflate a menu with the following method.

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.my_menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

This question was already asked here. And i tried all the answers its not working.

My issue is Everything working fine.but when i open another fragment(it have not any option menu) and get back to previous view pager fragment while clicking menu item onOptionsItemSelected not firing. When i swipe fragment in viewpager and come back to the previous one, when i click menu item its firing.


回答1:


Its because viewpager maintain 3 fragment alive at a time. so when you come back, it set menu visibility status true to last fragment. thats why your menu item click not firing.

Use the following in the fragment where you keeping a viewpager in your case fragment A.

private boolean isInitial=true;

@Override
    public void onResume() {
        super.onResume();

        if (!isInitial) {
            int pos = viewpager.getCurrentItem();
            if (pageAdapter.getItem(pos).getUserVisibleHint() && pageAdapter.getItem(pos).isVisible()) {
                pageAdapter.getItem(pos).setMenuVisibility(true);
            }
        } else {
            isInitial = false;
        }
    }


来源:https://stackoverflow.com/questions/41583812/working-with-optionsmenu-in-nested-fragment-not-updating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!