Activity动态添加Fragment时遇到的问题

1.Activity动态调用代码

        TitleFragement a = new TitleFragement();
        getFragmentManager().beginTransaction().add(R.id.tt, a)
            .commit();

异常信息:

The specified child already has a parent.

经分析:

对应Fragment代码:

        View view = inflater.inflate(R.layout.titlefragement, container);
应改成:

        View view = inflater.inflate(R.layout.titlefragement, container, false);
查看定义:

    /**
     * Inflate a new view hierarchy from the specified xml resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param resource ID for an XML layout resource to load (e.g.,
     *        <code>R.layout.main_page</code>)
     * @param root Optional view to be the parent of the generated hierarchy.
     * @return The root View of the inflated hierarchy. If root was supplied,
     *         this is the root View; otherwise it is the root of the inflated
     *         XML file.
     */
    public View inflate(int resource, ViewGroup root) {
        return inflate(resource, root, root != null);
    }

 public View inflate(int resource, ViewGroup root, boolean attachToRoot)

    /**
     * Inflate a new view hierarchy from the specified xml resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param resource ID for an XML layout resource to load (e.g.,
     *        <code>R.layout.main_page</code>)
     * @param root Optional view to be the parent of the generated hierarchy (if
     *        <em>attachToRoot</em> is true), or else simply an object that
     *        provides a set of LayoutParams values for root of the returned
     *        hierarchy (if <em>attachToRoot</em> is false.)
     * @param attachToRoot Whether the inflated hierarchy should be attached to
     *        the root parameter? If false, root is only used to create the
     *        correct subclass of LayoutParams for the root view in the XML.
     * @return The root View of the inflated hierarchy. If root was supplied and
     *         attachToRoot is true, this is root; otherwise it is the root of
     *         the inflated XML file.
     */

root:需要附加到resource资源文件的根控件,什么意思呢,就是inflate()会返回一个 View对象,如果第三个参数attachToRoot为true,就将这个root作为根对象返回,否则仅仅将这个root对象的 LayoutParams属性附加到resource对象的根布局对象上,也就是将布局文件resource的布局参数转换为外层root可以接受的类 型,比如root是一个LinearLayout自己要转换的resource里面有layout_width=”fill_parent”,和 layout_height=”fill_parent”参数,但是这些参数没有外部环境,它们对应的对象都是 ViewGroup.LayoutParams对象,root参数让系统将ViewGroup.LayoutParams对象转换为 LinearLayout.LayoutParams对象。

attachToRoot:是否将root附加到布局文件的根视图上

用两个参数的,attachToRoot实际为true返回的是一个跟对象,用false的,可以添加到Activity上

原文地址:https://www.cnblogs.com/niuge/p/4622648.html