gpt4 book ai didi

java - 如何阻止使用 LayoutInflater().inflate(int resource, ViewGroup root, boolean AttachToRoot) 引发 IllegalStateExceptions?

转载 作者:行者123 更新时间:2023-12-01 08:02:51 24 4
gpt4 key购买 nike

我最近在设置具有 3 个 fragment 的 viewpager 时遇到了一个问题。当应用程序运行时,它崩溃并显示

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first

这里是创建要传递给 pageAdapter 的 fragment 列表的代码。

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

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

return list;

除了使用不同的布局创建之外,每个 fragment 本质上都是相同的。这是我为其中一个 fragment 提供的原始代码。公共(public)类 Fragment1 扩展 Fragment {

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

但是当我像这样运行它时,它不断崩溃并出现 IllegalStateException。我发现问题出在正在创建的 fragment 上。经过一番谷歌搜索后,我尝试将 fragment 的代码更改为此。

公共(public)类 Fragment1 扩展 Fragment {

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

return v;
}
}

这解决了问题,我不再收到 IllegalStateException,但我不知道这是如何工作的。这个 boolean 值到底有什么作用?这个异常(exception)意味着什么?我曾尝试按照建议添加方法调用,但这并没有解决问题。我也尝试将此 boolean 值更改为 true,但再次遇到相同的错误。 android文档说它是attachToRoot,但这不是我想要做的吗?将我的 3 个 fragment 附加到 rootview,哪个是 viewpager?如果有人能解释这一点,我们将不胜感激。

最佳答案

LayoutInflater.inflate() 的 3-arg 版本的 boolean 参数确定 LayoutInflater 是否将 inflatedView 添加到指定容器。对于Fragment,您应该指定false,因为Fragment本身会将返回的View添加到容器中。如果您传递 true 或使用 2-arg 方法,LayoutInflater 会将 View 添加到容器中,然后 Fragment 稍后会尝试再次执行此操作,这会导致 IllegalStateException.

关于java - 如何阻止使用 LayoutInflater().inflate(int resource, ViewGroup root, boolean AttachToRoot) 引发 IllegalStateExceptions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23878620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com