如何实现动态添加布局文件(避免 The specified child already has a parent的问题)

首先扯点别的:我应经连续上了两个星期的班了,今天星期一。是第三个周。这个班上的也是没谁了。最近老是腰疼。估计是累了。最近也没跑步。今天下班继续跑起。

这篇文章讲一讲如何在一个布局文件中动态加在一个布局文件。避免出现 The specified child already has a parent. You must call removeView() on the child’s parent first. 的问题。先看一看效果再说。

这里写图片描述

Activity 的布局文件 activity_add_view.xml 文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.administrator.learnaddview.AddViewActivity">

<!--我们要在LinearLayout里面动态添加布局 现在这个LinearLayout里面只有三个textView-->
    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="textView1"
            android:textSize="30dp" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="textView2"
            android:textSize="30dp" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="textView3"
            android:textSize="30dp" />
    </LinearLayout>

<!--一个按钮用来添加布局-->
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_input_add" />

</android.support.design.widget.CoordinatorLayout>

布局文件里有一个线性布局android:id="@+id/linearLayout"。我们动态把View添加到这个线性布局。

然后是AddViewActivity.java代码

public class AddViewActivity extends AppCompatActivity {

    private ViewGroup parentViewGroup; //父布局
    /**
     * A static list of country names.
     */
    private static final String[] COUNTRIES = new String[] {
        "Belgium", "France", "Italy", "Germany", "Spain",
        "Austria", "Russia", "Poland", "Croatia", "Greece",
        "Ukraine",
    };

    @
    Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_view);
        //找到想动态添加子view的布局容器就是上面布局中的LinearLayout
        parentViewGroup = (ViewGroup) findViewById(R.id.linearLayout);

        //找到浮动按钮并添加监听事件
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        if(fab != null) {
            fab.setOnClickListener(new View.OnClickListener() {@
                Override
                public void onClick(View view) {
                    //注释1处,inflate要被添加的子布局
                    final ViewGroup childViewGroup = (ViewGroup)
                    LayoutInflater.from(AddViewActivity.this).inflate(R.layout.beaddlayout,
                        parentViewGroup, false);
                        
                    //注释2处,子布局中的TextView控件
                    TextView textView = (TextView) childViewGroup.findViewById(R.id.text1);
                    //给textview随机设置一个文本
                    textView.setText(COUNTRIES[(int)(Math.random() * COUNTRIES.length)]);
                    //子布局中的ImageButton控件
                    ImageButton imageButton = (ImageButton) childViewGroup.findViewById(R.id.delete_button);
                    //给imageButton设置监听事件,当点击的时候就把这个刚添加的子布局从其父布局中删除掉
                    imageButton.setOnClickListener(new View.OnClickListener() {@
                        Override
                        public void onClick(View v) {
                            parentViewGroup.removeView(childViewGroup);
                        }
                    });
                    //注释3处,添加到线性布局parentViewGroup中
                    parentViewGroup.addView(childViewGroup);

                }
            });
        }
    }

}

注释1处,inflate要被添加的子布局。R.layout.beaddlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="?android:listPreferredItemHeightSmall"
    android:divider="?android:dividerVertical"
    android:dividerPadding="8dp"
    android:gravity="center"
    android:orientation="horizontal"
    android:showDividers="middle">

    <!-- 随机显示一个字符串 -->
    <TextView
        android:id="@+id/text1"
        style="?android:textAppearanceMedium"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingLeft="?android:listPreferredItemPaddingLeft" />

    <!-- 当按钮点击的时候会把这个布局文件从其父布局中移除-->
    <ImageButton
        android:id="@+id/delete_button"
        android:layout_width="48dp"
        android:layout_height="match_parent"
        android:background="?android:selectableItemBackground"
        android:contentDescription="remove"
        android:src="@drawable/ic_list_remove" />
</LinearLayout>

下面来仔细讲解一下实现步骤

1. 找到想添加布局的父布局

//找到想动态添加子view的布局容器就是上面布局中的LinearLayout
 parentViewGroup = (ViewGroup) findViewById(R.id.linearLayout);

2. 过滤将要被添加的布局文件到父布局中,父布局就是第一步骤中的parentViewGroup

//要被添加的子布局
 /*inflate方法有三个参数
 第一个参数:R.layout.beaddlayout 要被加载的布局
 第二个参数:parentViewGroup 要被加载到那里
 第三个参数:取值有true和false两种,等会我们试一试取值为true的情况*/
 final ViewGroup childViewGroup = (ViewGroup)
 LayoutInflater.from(AddViewActivity.this).inflate(R.layout.beaddlayout, parentViewGroup, false);

3:这一步是可选的。通过childViewGroup找到其中的iew,并添加监听事件等等操作。

/*子布局中的TextView控件*/
TextView textView = (TextView) childViewGroup.findViewById(R.id.text1);
textView.setText(COUNTRIES[(int)(Math.random() * COUNTRIES.length)]);

//子布局中的ImageButton控件
ImageButton imageButton = (ImageButton) childViewGroup.findViewById(R.id.delete_button);
//给imageButton设置监听事件,当点击的时候就把这个刚添加的子布局从其父布局中删除掉
imageButton.setOnClickListener(new View.OnClickListener() {@
    Override
    public void onClick(View v) {
        //parentViewGroup.removeView(childViewGroup);
        parentViewGroup.removeView(childViewGroup);
    }
});

4:把子布局添加到父布局中。大功告成。

 parentViewGroup.addView(childViewGroup);

在上面的第二步中,如果把最后一个参数取值为true,然后再调用 parentViewGroup.addView(childViewGroup); 的时候就会出现 the specified child already has a parent ,you must call the removeView() …的问题。

/**/
final ViewGroup childViewGroup = (ViewGroup)
//第三个参数取值为true
 LayoutInflater.from(AddViewActivity.this).inflate(R.layout.beaddlayout, parentViewGroup, true);

这是为啥呢?我们看看 LayoutInflater 的 inflate 方法的源码精简版

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
    synchronized(mConstructorArgs) {

        final Context inflaterContext = mContext;
        final AttributeSet attrs = Xml.asAttributeSet(parser);
        Context lastContext = (Context) mConstructorArgs[0];
        mConstructorArgs[0] = inflaterContext;
        //注释1处,result是root
        View result = root;

        //...
        // Temp is the root view that was found in the xml
        //注释2处,temp是我们要过滤的View
        final View temp = createViewFromTag(root, name, inflaterContext, attrs);

        ViewGroup.LayoutParams params = null;

        if(root != null) {
            // Create layout params that match root, if supplied
            params = root.generateLayoutParams(attrs);
            if(!attachToRoot) {
                // Set the layout params for temp if we are not
                // attaching. (If we are, we use addView, below)
                temp.setLayoutParams(params);
            }
        }

        // Inflate all children under temp against its context.
        rInflateChildren(parser, temp, attrs, true);
        
        // We are supposed to attach all the views we found (int temp)
        // to root. Do that now.
        if(root != null && attachToRoot) {
            //注释3处,将temp添加到root中,这里的root是注释1处的result
            root.addView(temp, params);
        }

        if(root == null || !attachToRoot) {
            //注释4处,result是temp,就是我们要过滤的View。
            result = temp;
        }
        //返回result
        return result;
    }
}

注释1处,result是root。
注释2处,temp是我们要过滤的View。
注释3处,如果父布局不为null,并且 attachToRoot =true。那么就会将过滤出来的子View添加到父布局的话,并返回父布局。

通过上面的分析就知道原因了:

如果父布局不为null,并且 attachToRoot = true。LayoutInflater 的 inflate 方法内部会将过滤出来的子View添加到父布局的话,并返回父布局。

结尾:我的文章写得比较菜,欢迎大家提出疑问和指出错误。行,歇一歇,喝杯水。

2024.04.09 回顾。光阴似箭,日月如梭呀。这都快8年了。。。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值