Android - getSupportFragmentManager返回null

时间:2015-08-30 16:24:44

标签: android android-fragments fragmentmanager

我正在尝试使用它的标签获取片段的特定实例,但我使用的是viewpager,这使得事情变得困难。我用过:

public Fragment getFragmentByPosition(int pos) {
    String tag = "android:switcher:" + R.id.pager + ":" + pos;
    FragmentManager fragmentManager = this.getSupportFragmentManager();
    Fragment fragment = fragmentManager.findFragmentByTag(tag);
    return fragment;
}

找到片段,但getSupportFragmentManager返回null。

上面的方法是在viewpager适配器类之外的活动中,我对这里要做什么感到很遗憾。任何帮助都将受到高度赞赏,谢谢!

1 个答案:

答案 0 :(得分:0)

您可以从此处使用SmartViewPager https://gist.github.com/jacek-marchwicki/d6320ba9a910c514424d

从此类扩展您的视图寻呼机,并使用getActiveFragment方法获取片段。您还可以更改此方法的实现,以通过TAG名称获取片段。

public Fragment getActiveFragment(String name) {
    final Fragment fragmentByTag = fragmentManager.findFragmentByTag(name);
    if (fragmentByTag == null) {
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        fragmentManager.dump("", null, new PrintWriter(outputStream, true), null);
        final String s = new String(outputStream.toByteArray(), Charsets.UTF_8);
        throw new IllegalStateException("Could not find fragment via hacky way.\n" +
                "We were looking for name: " + name + "\n" +
                "Fragment with this name does not exists, or hack stopped working.\n" +
                "Current fragment manager dump is: " + s);
    }
    return fragmentByTag;
}