首先,有View。inflate()和Layoutinflater。inflate()两个方法,但看一下源码就知道其实是一种:
public static View inflate(Context context, int resource, ViewGroup root) { LayoutInflater factory = LayoutInflater.from(context); return factory.inflate(resource, root); }
再者,获取LayoutInflater对象的方法,不止上面写的LayoutInflater.from(context)一种,另外还有两种,现在总结一下:
LayoutInflater factory=LayoutInflater.from(this); LayoutInflater factory=getLayoutInflater(); LayoutInflater factory=(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
-->现在查看一下每一种方法的内部实现源码:
-->第一种方法的源码:
/** LayoutInflater.class * Obtains the LayoutInflater from the given context. */ 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; }
-->评析:LayoutInflater.from(context)方法调用的是“第三种方法”:context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-->第二种方法源码:
/** Activity.class * Convenience for calling * {@link android.view.Window#getLayoutInflater}. */ public LayoutInflater getLayoutInflater() { return getWindow().getLayoutInflater(); }
-->评析:Activity.getLayoutInflater()方法调用的是Window.getLayoutInflater()方法:
/** Window.class * Quick access to the {@link LayoutInflater} instance that this Window * retrieved from its Context. * * @return LayoutInflater The shared LayoutInflater. */ public abstract LayoutInflater getLayoutInflater();
-->评析:但是Window.getLayoutInflater()方法找不到调用方法了。通过它的方法描述大概可以知道也是调用“第三种方法”:context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-->第三种方法的源码:
/** Activity.class*/
@Override public Object getSystemService(String name) { if (getBaseContext() == null) { throw new IllegalStateException( "System services not available to Activities before onCreate()"); } if (WINDOW_SERVICE.equals(name)) { return mWindowManager; } else if (SEARCH_SERVICE.equals(name)) { ensureSearchManager(); return mSearchManager; } return super.getSystemService(name); }
-->评析:this.getSystemService(LAYOUT_INFLATER_SERVICE)方法调用的是其父类的getSystemService(LAYOUT_INFLATER_SERVICE);
public class Activity extends ContextThemeWrapper
-->评析:从上面的代码知道,Activity类的父类是ContextThemeWrapper类。
/** ContextThemeWrapper.class */ @Override public Object getSystemService(String name) { if (LAYOUT_INFLATER_SERVICE.equals(name)) { if (mInflater == null) { mInflater = LayoutInflater.from(mBase).cloneInContext(this); } return mInflater; } return mBase.getSystemService(name); }
-->评析:下面看看mBase是什么:
public class ContextThemeWrapper extends ContextWrapper { private Context mBase;
...
-->评析:ContextThemeWrapper.getSystemService(LAYOUT_INFLATER_SERVICE)方法调用的是Context.getSystemService(LAYOUT_INFLATER_SERVICE)方法:
/** Context.class */ public abstract Object getSystemService(String name);
-->评析:追根溯源暂时只能到这了。我也不知道它是怎么实现了,或许在Context的子类中有实现。我已经不想去找了。