gpt4 book ai didi

android - fragment - 获取 View 在调用 onCreateView 时已经有父错误

转载 作者:行者123 更新时间:2023-11-29 19:33:49 24 4
gpt4 key购买 nike

我在运行时从 Activity 中扩充 fragment 。因此,为了膨胀 fragment 类中 fragment 的 View ,我调用了:

  @Nullable
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.confirm_fragment, container);
}

此时我遇到日志崩溃:

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

但是如果我将我的方法修改为:

      @Nullable
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.confirm_fragment, null);
}

我现在将我的容器指定为 null,它起作用了。但我不明白的是,我在哪里为崩溃的代码中的 View 指定父 View ?

最佳答案

阅读自this link这就是为什么以及何时在 attachToRoot 参数中传递父容器的实例或 null。

来自链接:

Button button = (Button) inflater.inflate(R.layout.custom_button, mLinearLayout, false);
mLinearLayout.addView(button);

By passing in false, we say that we do not want to attach our View to the root ViewGroup just yet. We are saying that it will happen at some other point in time. In this example, the other point in time is simply the addView() method used immediately below inflation.

所以如果你膨胀:

return inflater.inflate(R.layout.confirm_fragment, container);

首先它会立即将 confirm_fragment 附加到容器。返回 View 后,将尝试隐式再次将 fragment 添加到父级,但由于已经添加,将抛出异常:

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

希望你明白了。

关于android - fragment - 获取 View 在调用 onCreateView 时已经有父错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39503521/

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