findFragmentByTag()仅在ActioBar的第三个选项卡上返回null [英] findFragmentByTag() returns null only on the third tab of the ActioBar

本文介绍了findFragmentByTag()仅在ActioBar的第三个选项卡上返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用由Android提供的带有标签的活动,并带有 android.support.v7.app.ActionBar.TabListener ViewPager FragmentPagerAdapter 。父级活动包含并管理三个 Fragment 。另外,父活动具有保存片段提供的数据的方法。为了获取其中定义的数据(而不是由父活动发送),我编写了以下代码:

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());

其中 getActiveFragment()

        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;
        }

实际上,我遇到以下问题:当我尝试保存由提供的数据时在这三个片段中,我有一个 java.lang.NullPointerException 由第三个片段(为null)引起。仅当我没有在设备上显示第二或第三片段时,才会发生这种情况。
我不明白如何避免和解决此问题。
有任何建议吗?

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?

推荐答案

这是因为如果仅第一个选项卡/片段被创建,则不会创建第三个片段如图所示。
默认情况下,ViewPager会在内部准备可见的片段,即它的左边和右边。
尝试

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)

这篇关于findFragmentByTag()仅在ActioBar的第三个选项卡上返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆