下面是关于 LayoutInflater 简单用法:
直接看例子,我想在 activity_main 文件中动态的添加一个布局;下面是 activity_main 文件中的代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/rl_root">

</RelativeLayout>

里面只有一个容器 RelativeLayout ;下面看另一个布局 item_main :

<!-- 动态添加布局时一定要在外层加RelativeLayout,否则layout属性无效-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical">

        <Button
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="按钮1" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="按钮2" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="按钮3" />

    </LinearLayout>
</RelativeLayout>

也很简单,里面有一个容器和三个 Button ,那么就可以将 item_main 文件动态添加到  activity_main 文件了:

RelativeLayout rl_root;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rl_root = findViewById(R.id.rl_root);

        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View view = layoutInflater.inflate(R.layout.item_main,null,false);
        rl_root.addView(view);
    }

这样便添加完成了。

其中 inflate() 方法中三个参数分别为:需要加载的布局;给该布局的外部再嵌套一层父布局,不需要传 null ;

第三个参数有些复杂,单独说:

如果第二个参数传 null ,那个第三个参数也不用传,传什么都没有意义;

如果第二个参数传了,第三个参数传 true,则会给加载的布局文件的指定一个父布局;如果第三个参数传 false ,则会将布局文件最外层的所有 layout 属性进行设置,当该 view 被添加到父 view 当中时,这些 layout 属性会自动生效。

可以看出我在上面,第二个参数传的 null ,也就是我们没有在外面为它指定一个父布局,那么 layout 属性也就无效;最简单的解决方式就是在外层加一个 RelativeLayout ,也就是我上面的写法~~

到这里就结束了~