LayoutInflater的获取
- 在Activity中:getLayoutInflater()
- LayoutInflater.from(this)
- getSystemService(LAYOUT_INFLATER_SERVICE)
第一种方法中,rerutn getWindow().getLayoutInflater(),查看PhoneWindow源码可知,在PhoneWindow中被初始化,也就是调用的方法二。
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(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;
}
也就是调用的方法三。。。所以呢,三个方法没啥区别,怎么简单怎么来
调用getSystemService方法获取所需服务
//ContextImpl.java
public Object getSystemService(String name) {
return SystemServiceRegistry.getSystemService(this, name);
}
//SystemServiceRegistry.java
private static final HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =
new HashMap<String, ServiceFetcher<?>>();
static{
registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
new CachedServiceFetcher<LayoutInflater>() {
@Override
public LayoutInflater createService(ContextImpl ctx) {
return new PhoneLayoutInflater(ctx.getOuterContext());
}});
}
public static Object getSystemService(ContextImpl ctx, String name) {
ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
return fetcher != null ? fetcher.getService(ctx) : null;
}
从代码中可以知道,LayoutInflater(抽象类)最后获取的实现类是PhoneLayoutInflater
getLayoutInflater().inflate();
这个是重点,也就是这里解析了布局文件并返回了view。
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser); //解析属性
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
View result = root;
try {
final String name = parser.getName();
//merge标签的直接解析,并且添加上去,必须要有父view
if (TAG_MERGE.equals(name)) {
if (root == null || !attachToRoot) {
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// 解析xml并创建名字为name的view,也就是最外层的view
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
//root不为空且需要attach时设置解析的view的LayoutParams
if (root != null) {
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
//根据父view解析子view
rInflateChildren(parser, temp, attrs, true);
if (DEBUG) {
System.out.println("-----> done inflating children");
}
//inflate时传入了parent即root且attachToRoot为true,则把解析的view添加到root中
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// 如果没有传入parent或者attachToRoot为false时,把解析的view作为返回值
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
final InflateException ie = new InflateException(e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (Exception e) {
final InflateException ie = new InflateException(parser.getPositionDescription()
+ ": " + e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
return result;
}
}
重要的方法:
- rInflate(parser, root, inflaterContext, attrs, false); 解析view
- createViewFromTag(root, name, inflaterContext, attrs); 创建父view
- rInflateChildren(parser, temp, attrs, true); 解析子view,调用的也是rInflate解析
//rInflate方法
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
final int depth = parser.getDepth();
int type;
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
if (TAG_REQUEST_FOCUS.equals(name)) {//requestFocus
parseRequestFocus(parser, parent);
} else if (TAG_TAG.equals(name)) { //tag
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) { //include
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {//merge
throw new InflateException("<merge /> must be the root element");
} else {//解析view
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflateChildren(parser, view, attrs, true);//解析子view
viewGroup.addView(view, params);//添加到父view中
}
}
if (finishInflate) {//当name为merge时为false
parent.onFinishInflate();
}
}
//解析子view
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) {
return createViewFromTag(parent, name, context, attrs, false);
}
//根据name创建view
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
// Apply a theme wrapper, if allowed and one is specified.
if (!ignoreThemeAttr) {
final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
final int themeResId = ta.getResourceId(0, 0);
if (themeResId != 0) {
context = new ContextThemeWrapper(context, themeResId);
}
ta.recycle();
}
if (name.equals(TAG_1995)) {
// Let's party like it's 1995!
return new BlinkLayout(context, attrs);
}
try {
View view;
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, context, attrs);//默认返回null,Activity#onCreateView
} else if (mFactory != null) {
view = mFactory.onCreateView(name, context, attrs); //默认返回null,Activity#onCreateView
} else {
view = null;
}
if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, context, attrs);
}
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
if (-1 == name.indexOf('.')) {//系统的view
view = onCreateView(parent, name, attrs);
} else {//自定义view
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
return view;
} catch (InflateException e) {
throw e;
} catch (ClassNotFoundException e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name, e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (Exception e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name, e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
}
}
最终调用LayoutInflater#createView创建了view
static final Class<?>[] mConstructorSignature = new Class[] {
Context.class, AttributeSet.class};//指定了布局文件中的view,创建实例时采用的构造器
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
Constructor<? extends View> constructor = sConstructorMap.get(name); //构造器
if (constructor != null && !verifyClassLoader(constructor)) {
constructor = null;
sConstructorMap.remove(name);
}
Class<? extends View> clazz = null;
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
if (constructor == null) {
// Class not found in the cache, see if it's real, and try to add it
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class); //反射得到View
if (mFilter != null && clazz != null) {
//省略
}
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
sConstructorMap.put(name, constructor);//缓存构造器
} else {
// If we have a filter, apply it to cached constructor
if (mFilter != null) {
//省略
}
}
Object[] args = mConstructorArgs;//Context
args[1] = attrs; //属性
final View view = constructor.newInstance(args);//初始化View
if (view instanceof ViewStub) {
// Use the same context when inflating ViewStub later.
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
return view;
} catch (NoSuchMethodException e) {
//省略
}
}
mFilter正常情况下为null,可以通过setFilter设置,可以用来限定布局中是否可以加载指定的View,当不能加载时会抛出InflateException异常
整体的加载流程
Activity#setContentView
-->AppCompatDelegateImplV9#setContentView
-->LayoutInflater.from(this.mContext).inflate(resId, contentParent)
-->LayoutInflater#rInflateChildren
-->LayoutInflater#rInflate
-->LayoutInflater#createViewFromTag
-->LayoutInflater#onCreateView
-->LayoutInflater#createView