【问题标题】:How did I stop IllegalStateExceptions from being thrown with LayoutInflater().inflate(int resource, ViewGroup root, boolean attachToRoot)?我如何阻止 IllegalStateExceptions 被 LayoutInflater().inflate(int resource, ViewGroup root, boolean attachToRoot) 抛出?
【发布时间】:2014-05-27 07:51:07
【问题描述】:

我最近在设置一个包含 3 个片段的查看器时遇到了一个问题。当应用程序运行时它崩溃了

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;
}
} 

但是当我像这样运行它时,它一直因 IllegalStateException 而崩溃。我发现问题来自正在创建的片段。经过一番谷歌搜索后,我尝试将片段的代码更改为此。

公共类 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,除非我不知道它是如何工作的。这个布尔值究竟是做什么的?这个例外是什么意思?我曾尝试像建议的那样添加方法调用,但这并没有解决它。我也尝试将此布尔值更改为 true,但我再次遇到相同的错误。 android 文档说它的 attachToRoot 但这不是我想要做的吗?将我的3个片段附加到rootview,即viewpager?如果有人能解释这一点,将不胜感激。

【问题讨论】:

    标签: java android android-fragments layout-inflater illegalstateexception


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多