LayoutInflater & Factory2

关于作者:CSDN内容合伙人、技术专家, 从零开始做日活千万级APP。
专注于分享各领域原创系列文章 ,擅长java后端、移动开发、商业变现、人工智能等,希望大家多多支持。
未经允许不得转载

目录

  • 一、导读
  • 二、概览
  • 三、使用
    • 3.1 LayoutInflater 实例获取
    • 3.2 调用 inflate 方法解析
    • 3.3
  • 四、 LayoutInflater.Factory (2)
    • 4.1 使用
    • 4.2 注意点
  • 五、 推荐阅读

在这里插入图片描述

一、导读

我们继续总结学习基础知识,温故知新。

我们在学习布局加载原理的时候,用到了这个类,他的作用还是很多的,这里我们花点时间集中来看一看。
再深入学习一番。

二、概览

LayoutInflater 的作用是将布局XML文件实例化为其相应的View对象,是一个视图填充器。
除了基本的布局解析功能,LayoutInflater 还可以用于实现 动态换肤、 视图转换、 属性转换等多种功能。

这是一个抽象类,下面我们进入学习模式。

public abstract class LayoutInflater

三、使用

3.1 LayoutInflater 实例获取


//1 如果是在 Activity 或 Fragment 可直接获取到实例
LayoutInflater inflater = getLayoutInflater();//调用Activity的getLayoutInflater()

//2 通过 LayoutInflater 的静态方法 from 获取
LayoutInflater inflater = LayoutInflater.from(context);

//3 通过系统服务 getSystemService 方法获取
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

其实最后都是调用context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);来获取,我们一起看看源码

ContextImpl.java

    @Override
    public Object getSystemService(String name) {
   
        return SystemServiceRegistry.getSystemService(this, name);
    }

SystemServiceRegistry.java


    /**
     * Gets a system service from a given context.
     * @hide
     */
    public static Object getSystemService(ContextImpl ctx, String name) {
   

        // 这是一个ArrayMap,在启动时就填充好了数据,我们根据名字来查找对应的service
        final ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
        
        final Object ret = fetcher.getService(ctx);
        
        return ret;
    }

在看看初始化

    private static final Map<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =
                new ArrayMap<String, ServiceFetcher<?>>();
    static {
   
        
        registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
                new CachedServiceFetcher<LayoutInflater>() {
   
            @Override
            public LayoutInflater createService(ContextImpl ctx) {
   
                return new PhoneLayoutInflater(ctx.getOuterContext());
            }});
        
    }
    
    private static <T> void registerService(@NonNull String serviceName,
        @NonNull Class<T> serviceClass, @NonNull ServiceFetcher<T> serviceFetcher) {
   
        SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
        SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
        SYSTEM_SERVICE_CLASS_NAMES.put(serviceName, serviceClass.getSimpleName());
    }

再来看看 CachedServiceFetcher

    static abstract class CachedServiceFetcher<T> implements ServiceFetcher<T> {
   

        @Override
        public final T getService(ContextImpl ctx) {
   

            T ret = null;

            for (

你可能感兴趣的:(Android基础,java,开发语言,android)