简体   繁体   English

Android - 无法再次打开片段

[英]Android - Can not open fragment a second time

I'm opening a fragment and soon after closing it. 我打开一个fragment ,很快关闭它。

It opens and closes no problem the first time but the second time it tries to open it gives a NullPointerException . 它第一次打开和关闭没有问题,但第二次尝试打开它会产生NullPointerException

To open the fragment with SomeFrag class that extends Fragment . 要打开fragmentSomeFrag扩展类Fragment To close it I call closeFrag() method. 要关闭它,我调用closeFrag()方法。

public class SomeFrag extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootview = (ViewGroup) inflater.inflate(R.layout.somefrag, container, false); // line with error
        return mRootview;
    }

    public void closeFrag(){
        ((ViewGroup)mRootview.getParent()).removeView(mRootview);
    }
}

Why am I not able to open the fragment a second time? 为什么我无法再次打开片段?

例如,要删除片段,您应该使用事务

getSupportFragmentManager().beginTransaction().remove(fragmentInstance).commit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM