布局加载器——LayoutInflate

1 LayoutInflate基本使用

1.1 LayoutInflate使用场景

LayoutInflate是什么?

答:一个用于加载布局的系统服务,就是实例化与Layout XML文件对应的View对象,称之为布局加载器,不能直接使用, 需要通过getLayoutInflater( )方法或getSystemService( )方法来获得与当前Context绑定的 LayoutInflater实例!

在介绍LayoutInflate使用,可以回顾一下哪些地方用过LayoutInflate:

  • 在Activity中
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.activity_main, null);
  • 在Fragment中
        View view = inflater.inflate(R.layout.fragment_guide_one, container, false);
        return view;
  • 在Adapter中
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
   
        View view = LayoutInflater.from(convertView.getContext()).inflate(R.layout.activity_main, parent, false);
        return view;
    }
  • 某些特殊情况下,需要使用LayoutInflate
        LayoutInflater inflater  =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

这些使用场景都有一个共同的特点:需要将一个XML布局文件转化为View,LayoutInflate的主要功能就是将XML文件实例化为相应的Veiw对象。

1.2 LayoutInflate简单使用

关于LayoutInflate的简单使用流程如下:

  1. 获取LayoutInflate的实例
  2. 调用加载布局的方法
  3. 通过LayoutInflate.LayoutParams设置相关属性

LayoutInflate本身是一个抽象类,不可以直接通过new的方式去获得它的实例,主要有以下三种方法:

LayoutInflater inflater1 = LayoutInflater.from(context); 
LayoutInflater inflater2 = getLayoutInflater();  // 在Activity中调用
LayoutInflater inflater3 = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); 

三种方法的底层实现其实一样

这里看一下前两种方法的底层实现:

public static LayoutInflater from(Context context) {
   
    LayoutInflater LayoutInflater =
            (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (LayoutInflater == null) {
   
        throw new AssertionError("LayoutInflater not found.");
    }
    return LayoutInflater;
}

在Activity内部调用getLayoutInflater方法,其实是调用PhoneWindow的mLayoutInflate:

public PhoneWindow(Context context) {
   
    super(context);
    mLayoutInflater = LayoutInflater.from(context);
}

所以,这几个方法实际上殊途同归,都是通过调用Context的getSystemService方法去获取。获取到的是PhoneLayoutInflater这个实现类,具体的获取过程就不在这里展开分析了。

public class Policy implements IPolicy {
   
    ...
    public LayoutInflater makeNewLayoutInflater(Context context) {
   
        return new PhoneLayoutInflater(context);
    }
}  

关于加载布局的方法

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

该方法的三个参数依次是:

  • resource:要加载的布局对应的资源ID
  • root:为该布局的外部在嵌套一层父布局,如不需要,填写null即可
  • attachToRoot:是否为加载的布局文件的最外层嵌套一层root布局。root不为null,默认为true,如果为false,则root失去作用,如果root为null,attachToRoot无作用。

除了上述的加载布局方法,还有以下重载方法:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值