Android LayoutInflater 相关笔记

阅读文章:
1、Android LayoutInflater原理分析,带你一步步深入了解View(一)

1. 如果root为null,attachToRoot将失去作用,设置任何值都没有意义。

2. 如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root。

3. 如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,即会为
布局生成的实例根据root生成该实例的LayoutParams(因为LayoutParams会包含实例设置的各种layout_xxx
属性),当该view被添加到父view(准确的说应该是父ViewGroup)当中时,这些layout属性会自动生效。

4. 在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true

2、三个案例带你看懂LayoutInflater中inflate方法两个参数和三个参数的区别
3、Android角落 - LayoutInflater第三个参数


补充笔记:

往一个 Layout 中添加子布局的实现方法(假设情景为往一个 FrameLayout 中添加一个布局文件为sub_layout 的子布局,而该布局中只包含一个 Button):

sub_layout.xml

<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="300dp"
    android:layout_height="100dp"
    android:text="BUTTON"
    android:gravity="center">
</Button>

(1)inflate() 方法的参数 root 为 null 时,就需要利用 Layout 的 addView() 方法将实例化的子布局添加到布局中。示例代码如下:

LayoutInflater inflater = LayoutInflater.from(context);
View button=inflater.inflate(R.layout.sub_layout, null);
frameLayout.addView(button);

这里写图片描述
实现效果如上,但是此时设置的 layout_xxx 属性会失效,这是因为当 root 为空时,通过反射拿到的 View(即 Android LayoutInflater原理分析,带你一步步深入了解View(一)一文中的展示的源码 public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) 方法中提到的 temp 变量)是没有设置 LayoutParams 的。
此时为了实现预期效果,如 :

android:layout_width="300dp"
android:layout_height="100dp"

就需要为 button 设置 LayoutParams,如下:

LayoutInflater inflater = LayoutInflater.from(this);
View button=inflater.inflate(R.layout.sub_layout, null);
FrameLayout.LayoutParams param = new FrameLayout.LayoutParams(dp2px(300),dp2px(100));
button.setLayoutParams(param);
frameLayout.addView(button);

因为是往 FrameLayout 中添加子布局,所以需要设置 FrameLayout.LayoutParams 类型的。

(2)inflate() 方法的参数 root 不为 null 时( 此时 inflate(resource,root) 方法中 attachToRoot 默认为 true ),可以直接使用

//attachToRoot 需要为true,
//否则不会将 R.layout.sub_layout 添加到 frameLayout 中,
//就需要手动 addView() 了
inflater.inflate(R.layout.sub_layout, frameLayout, true);

或者

View button=inflater.inflate(R.layout.sub_layout, frameLayout, false);
frameLayout.addView(button);

来实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值