LayoutInflater的说明

    xiaoxiao2023-10-12  160

    关于喜马拉雅项目中的LayoutInflater的使用说明

    private View createSuccessView(ViewGroup container) { LayoutInflater.from(this).inflate(R.layout.item_detail_list,container,false) return null; }

    作用是载一个界面进来 载入this界面 R.layout.item_detail_list是需要载入的界面 container 添加到的父容器 flase 没有学到自定义控件之前 用false

    我们首先看看LayoutInflater的工作原理是什么。在一个应用程序中,inflate()方法有两个可用的版本:

    1. inflate(int resource, ViewGroup root) 2. inflate(int resource, ViewGroup root, boolean attachToRoot)

    其中 inflate() 方法中三个参数分别为:需要加载的布局;给该布局的外部再嵌套一层父布局,不需要传 null ; 第三个参数有些复杂,单独说: 如果第二个参数传 null ,那个第三个参数也不用传,传什么都没有意义; 如果第二个参数传了,第三个参数传 true,则会给加载的布局文件的指定一个父布局;如果第三个参数传 false ,则会将布局文件最外层的所有 layout 属性进行设置,当该 view 被添加到父 view 当中时,这些 layout 属性会自动生效。 可以看出我在上面,第二个参数传的 null ,也就是我们没有在外面为它指定一个父布局,那么 layout 属性也就无效;最简单的解决方式就是在外层加一个 RelativeLayout ,

    第一种

    root != null, attachToRoot=true(默认也是true) LinearLayout root = (LinearLayout) findViewById(R.id.layout); View view1 = LayoutInflater.from(this).inflate(R.layout.item, root, true); View view2 = LayoutInflater.from(this).inflate(R.layout.item, root);

    结果: 返回的view是父容器(root)布局 item根布局的宽高属性生效 已经添加到父容器(root)中

    第二种

    root != null, attachToRoot=false LinearLayout root = (LinearLayout) findViewById(R.id.layout); View view1 = LayoutInflater.from(this).inflate(R.layout.item, root, false);

    结果: 返回item根布局 根布局的宽高属性生效 未添加到父容器(root)中

    第三种

    root == null,attachToRoot=false/true View view = LayoutInflater.from(this).inflate(R.layout.item, null, false); View view = LayoutInflater.from(this).inflate(R.layout.item, null, true); View view = LayoutInflater.from(this).inflate(R.layout.item, null);

    结果: 返回item根布局 根布局的宽高属性失效 未添加到父容器(root)中在这里插入代码片

    转自简书:你的益达233 链接:https://www.jianshu.com/p/a8f3824b1fe8

    最新回复(0)