Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/220.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我是如何阻止LayoutInflater()引发IllegalStateExceptions.inflate(int resource、ViewGroup root、boolean attachToRoot)的?_Java_Android_Android Fragments_Layout Inflater_Illegalstateexception - Fatal编程技术网

Java 我是如何阻止LayoutInflater()引发IllegalStateExceptions.inflate(int resource、ViewGroup root、boolean attachToRoot)的?

Java 我是如何阻止LayoutInflater()引发IllegalStateExceptions.inflate(int resource、ViewGroup root、boolean attachToRoot)的?,java,android,android-fragments,layout-inflater,illegalstateexception,Java,Android,Android Fragments,Layout Inflater,Illegalstateexception,我最近在设置带有3个片段的viewpager时遇到了一个问题。当应用程序运行时,它崩溃了 java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first 下面是创建要传递给pageAdapter的片段列表的代码 private Vector<Fragment> getFragments()

我最近在设置带有3个片段的viewpager时遇到了一个问题。当应用程序运行时,它崩溃了

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first
下面是创建要传递给pageAdapter的片段列表的代码

private Vector<Fragment> getFragments() {
    Vector<Fragment> list = new Vector<Fragment>();

    list.add(new Fragment1());
    list.add(new Fragment2());
    list.add(new Fragment3());

    return list;
但当我这样运行它时,它不断崩溃,出现了非法的例外。我发现问题来自于正在创建的片段。在谷歌搜索之后,我尝试将片段的代码更改为这个

公共类Fragment1扩展了Fragment{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    View v = getActivity().getLayoutInflater().inflate(R.layout.fragment1, container);
    return v;
}
} 
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View v = getActivity().getLayoutInflater().inflate(R.layout.fragment1, container, false);

    return v;
}
}

这解决了问题,我不再得到IllegalStateException,但我不知道它是如何工作的。这个布尔值到底是做什么的?这个异常意味着什么?我曾尝试像Suggest一样添加方法调用,但没有解决它。我还尝试将这个布尔值更改为true,但我再次遇到相同的错误。android文档说它是attachToRoot,但这不是我想要做的吗?将我的3个片段连接到rootview,即viewpager?如果有人能解释这一点,我将不胜感激。

3-arg版本的
LayoutInflater.inflate()的布尔参数
确定
LayoutInflater
是否会将膨胀视图添加到指定的容器中。对于片段,应指定
false
,因为片段本身会将返回的视图添加到容器中。如果传递
true
或使用2-arg方法,LayoutInflater会将视图添加到容器中,然后片段稍后将再次尝试这样做,这将导致
IllegalStateException

3-arg版本的
LayoutInflater.inflate()的布尔参数
确定
LayoutInflater
是否会将膨胀视图添加到指定的容器中。对于片段,应指定
false
,因为片段本身会将返回的视图添加到容器中。如果传递
true
或使用2-arg方法,LayoutInflater会将视图添加到容器中,然后,片段稍后将再次尝试这样做,这将导致
IllegalStateException