findFragmentByTag() returns null only on the third tab of the ActioBar

自古美人都是妖i 提交于 2019-12-12 01:53:16

问题


I am using a tabbed Activity provided by Android with android.support.v7.app.ActionBar.TabListener,ViewPager and FragmentPagerAdapter. The parent Activty cointains and manages three Fragment. In addition, the parent Activity has a method to save the data provided by the fragments. In order to get the data defined in them (and not sended by the parent Activity) I am wrote the following code:

MyFragment frag = (MyFragment) mSectionsPagerAdapter.getActiveFragment(mViewPager,1,getSupportFragmentManager());

Where getActiveFragment() is

        public Fragment getActiveFragment(ViewPager container, int position, FragmentManager mFragmentManager) {
            String name = makeFragmentName(container.getId(), position);
            return  mFragmentManager.findFragmentByTag(name);
        }


        private String makeFragmentName(int viewId, int index) {
            return "android:switcher:" + viewId + ":" + index;
        }

Actually, I have the following problem: when I try to save data provided by the three fragment, I have a java.lang.NullPointerException caused by the third fragment which is null. This happens only if I do not display on my device the second or third fragment. I do not understand how to avoid and fix this behaviour. Any suggestion?


回答1:


This is due to the third fragment not being created if only the first tab/fragment is shown. The ViewPager per default internally prepares the visible fragment, the one left to it and the one right to it. Try

viewpager.setOffscreenPageLimit(2)



来源:https://stackoverflow.com/questions/27680811/findfragmentbytag-returns-null-only-on-the-third-tab-of-the-actiobar

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