为什么我无法访问Fragment? (空指针异常)

时间:2017-09-17 20:25:55

标签: android android-fragments nullpointerexception android-viewpager

我有一个片段,它在XML布局的RelativeLayout中有两个已定义的片段,它们位于彼此的顶部。我想要做的是onCreateView隐藏第一个和后一个用开关按钮在两者之间切换。这就是OnCreateView的样子:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

ViewGroup rootView = (ViewGroup) inflater.inflate(
            R.layout.fragment_questions_slide_page, container, false);

FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.hide(getFragmentManager().findFragmentById(R.id.firstFragment));
ft.commit();

当我运行应用程序时,出现以下错误。有什么想法吗?

java.lang.NullPointerException: Attempt to read from field 'int android.support.v4.app.Fragment.mContainerId' on a null object reference
                                                                             at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1017)
                                                                             at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:976)
                                                                             at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:95)

如果它有所不同,Fragment由设置为ViewPager的PagerAdapter启动。

2 个答案:

答案 0 :(得分:0)

尝试使用getChildFragmentManager查找要隐藏/显示的片段。

此外,您应该在容器中搜索片段,而不是片段id

答案 1 :(得分:0)

来自@mohax的提示很好。这是工作代码:

    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(
            R.layout.fragment_questions_slide_page, container, false);

    FragmentTransaction transaction = getFragmentManager()
            .beginTransaction()
            .hide(getChildFragmentManager().findFragmentById(R.id.firstFragment))
    transaction.commit();

事务由getFragmentManager完成,并识别您必须调用getChildFragmentManager的片段。谢谢!