深入理解LayoutInflater
探究LayoutInflater的实现类##
在android程序员写代码的时候,很多时候会用到LayoutInflater来加载指定的布局:
LayoutInflater inflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);// 或者通过from(Context context)获取实例LayoutInflater inflater = LayoutInflater.from(context);inflater.inflate(int resource, ViewGroup root);
其实LayoutInflater是一个抽象类:
public abstract class LayoutInflater { ....}
既然是抽象类,那么一定有它的实现,我们知道系统会在ContextImpl中将所有的系统service,注入到ServiceFetcher中,关于”LAYOUT_INFLATER_SERVICE”有如下实现:
registerService(LAYOUT_INFLATER_SERVICE, new ServiceFetcher() { public Object createService(ContextImpl ctx) { return PolicyManager.makeNewLayoutInflater(ctx.getOuterContext()); }});
可以看到这里实际上是调用了PolicyManager.makeNewLayoutInflater
// Policy的实现类private static final String POLICY_IMPL_CLASS_NAME = "com.android.internal.policy.impl.Policy"; private static final IPolicy sPolicy; static { try { // 通过反射构造Policy对象 Class policyClass = Class.forName(POLICY_IMPL_CLASS_NAME); sPolicy = (IPolicy)policyClass.newInstance(); } ....}// 该方法会返回一个PhoneWindow对象public static Window makeNewWindow(Context context) { return sPolicy.makeNewWindow(context);}public static LayoutInflater makeNewLayoutInflater(Context context) { return sPolicy.makeNewLayoutInflater(context);}
可以看到上面的PolicyManager中的所有操作实际上是一个代理,具体的都是交给Policy类处理,Policy实现了Ipolicy接口
public class Policy implements IPolicy { private static final String TAG = "PhonePolicy"; private static final String[] preload_classes = { "com.android.internal.policy.impl.PhoneLayoutInflater", "com.android.internal.policy.impl.PhoneWindow", "com.android.internal.policy.impl.PhoneWindow$1", "com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback", "com.android.internal.policy.impl.PhoneWindow$DecorView", "com.android.internal.policy.impl.PhoneWindow$PanelFeatureState", "com.android.internal.policy.impl.PhoneWindow$PanelFeatureState$SavedState", }; static { // For performance reasons, preload some policy specific classes when // the policy gets loaded. for (String s : preload_classes) { try { Class.forName(s); } catch (ClassNotFoundException ex) { Log.e(TAG, "Could not preload class for phone policy: " + s); } } } // 创建PhoneWindow,也就是Activity中window的具体实现类 public Window makeNewWindow(Context context) { return new PhoneWindow(context); } // 可以看到LayoutInflater的具体实现类就是PhoneLayoutInflater public LayoutInflater makeNewLayoutInflater(Context context) { return new PhoneLayoutInflater(context); } public WindowManagerPolicy makeNewWindowManager() { return new PhoneWindowManager(); } public FallbackEventHandler makeNewFallbackEventHandler(Context context) { return new PhoneFallbackEventHandler(context); }}
此时,我们知道LayoutInflater的实现类其实就是PhoneLayoutInflater,下面我们看看PhoneLayoutInflater的源码
public class PhoneLayoutInflater extends LayoutInflater { private static final String[] sClassPrefixList = { "android.widget.", "android.webkit.", "android.app." }; .... @Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException { for (String prefix : sClassPrefixList) { try { // 核心代码就是调用LayoutInflater的createView方法,根据传入的控件名称name以及sClassPrefixList的构造对应的控件 // 比如name是Button,则View就是android.widget.Button View view = createView(name, prefix, attrs); if (view != null) { return view; } } catch (ClassNotFoundException e) { } } return super.onCreateView(name, attrs); } ....}
具体看下LayoutInflater#createView方法:
// 根据完整路径的类名根据反射构造对应的控件对象 public final View createView(String name, String prefix, AttributeSet attrs) throws ClassNotFoundException, InflateException { // 从缓存中获取当前控件的构造方法 Constructor<? extends View> constructor = sConstructorMap.get(name); Class<? extends View> clazz = null; try { // 如果缓存中没有,则获取当前控件全类名对应的Class,并且缓存其构造方法到sConstructorMap集合中 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); if (mFilter != null && clazz != null) { boolean allowed = mFilter.onLoadClass(clazz); if (!allowed) { failNotAllowed(name, prefix, attrs); } } constructor = clazz.getConstructor(mConstructorSignature); constructor.setAccessible(true); sConstructorMap.put(name, constructor); } else { ...... } Object[] args = mConstructorArgs; args[1] = attrs; // 通过反射构造当前view对象 final View view = constructor.newInstance(args); 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 (Exception e) { .... } finally { Trace.traceEnd(Trace.TRACE_TAG_VIEW); }}
LayoutInflater#createView方法比较简单,主要做了下面两件事:
1. 从sConstructorMap集合中获取当前View对应的构造方法,如果没有则根据当前全类名创建构造方法,并且存入sConstructorMap缓存中。
2. 根据构造方法,创建对应的View对象
探究LayoutInflater.inflate流程
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) { final Resources res = getContext().getResources(); .... // 通过传递的布局id,创建一个XmlResourceParser对象 final XmlResourceParser parser = res.getLayout(resource); try { return inflate(parser, root, attachToRoot); } finally { parser.close(); }} /** * * @param parser xml解析器 * @param root 需要解析布局的父视图 * @param attachToRoot 是否将解析的视图添加到父视图 * @return */ public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) { synchronized (mConstructorArgs) { final Context inflaterContext = mContext; final AttributeSet attrs = Xml.asAttributeSet(parser); Context lastContext = (Context) mConstructorArgs[0]; // Context对象 mConstructorArgs[0] = inflaterContext; // 存储当前父视图 View result = root; try { ...... final String name = parser.getName(); // 1.解析merge标签 if (TAG_MERGE.equals(name)) { if (root == null || !attachToRoot) { throw new InflateException(" can be used only with a valid " + "ViewGroup root and attachToRoot=true"); } rInflate(parser, root, inflaterContext, attrs, false); } else { // 2.通过xml的tag解析layout的根视图,比如LinearLayout final View temp = createViewFromTag(root, name, inflaterContext, attrs); ViewGroup.LayoutParams params = null; if (root != null) { // 生成布局参数 params = root.generateLayoutParams(attrs); // 3. 如果attachToRoot是false,表示不添加当前视图到父视图中,那么将params设置到自己的布局参数中 if (!attachToRoot) { temp.setLayoutParams(params); } } // 4. 解析temp视图中的所有子view rInflateChildren(parser, temp, attrs, true); // 如果root不是null,并且attachToRoot是true,那么将temp添加到父视图中,并设置对应的布局参数 if (root != null && attachToRoot) { root.addView(temp, params); } // 如果root是null,并且attachToRoot是false,那么返回的结果就是temp if (root == null || !attachToRoot) { result = temp; } } } .... return result;}
上述inflate方法主要做了下面的操作:
1. 单独解析merge标签,rInflate会将merge标签下的所有子View直接添加到根标签中
2. 通过createViewFromTag方法解析普通元素
3. 根据root和attachToRoot的状态,决定是否添加当前View对象到父视图中
4. 解析temp视图中的所有子view
createViewFromTag方法解析普通元素
可以看到,通过inflate加载视图中,解析单个元素的createViewFromTag是很常用的,下面先看看createViewFromTag方法:
private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) { return createViewFromTag(parent, name, context, attrs, false);}View createViewFromTag(View parent, String name, Context context, AttributeSet attrs, boolean ignoreThemeAttr) { if (name.equals("view")) { name = attrs.getAttributeValue(null, "class"); } try { View view; // 用户可以通过设置LayoutInflater的factory自行解析,如果没有设置则默认为null,所以这可以忽略这段 if (mFactory2 != null) { view = mFactory2.onCreateView(parent, name, context, attrs); } else if (mFactory != null) { view = mFactory.onCreateView(name, context, attrs); } else { view = null; } ..... if (view == null) { final Object lastContext = mConstructorArgs[0]; mConstructorArgs[0] = context; try { if (-1 == name.indexOf('.')) { // 这里是android内置的View控件,由于android自带的View控件,我们在使用的时候不需要全类名,所以这里是-1 view = onCreateView(parent, name, attrs); } else { // 自定义View控件的解析,自定义View必须写View的完整类名,比如" " view = createView(name, null, attrs); } } finally { mConstructorArgs[0] = lastContext; } } return view; } //省略catch代码}
我们知道对于系统自带的View会走到onCreateView方法创建,前面的分析已经知道当我们使用LayoutInflater的时候,其实是使用其实现类PhoneLayoutInflater,它复写了onCreateView方法,在该方法里同样会通过createView这样的方法创建对应的View对象,并且传入”android.widget.”这样的包名,这就是为什么我们使用系统自带的View控件时候,不需要写全类名的原因。
rInflateChildren方法解析所有子元素
上面的分析,我们已经知道在LayoutInflater#inflate方法中,当解析完根视图以后,会通过rInflateChildren解析当前根视图下的所有子视图
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException { rInflate(parser, parent, parent.getContext(), attrs, finishInflate);}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)) { parseRequestFocus(parser, parent); } else if (TAG_TAG.equals(name)) { parseViewTag(parser, parent, attrs); } else if (TAG_INCLUDE.equals(name)) { // 解析include标签 if (parser.getDepth() == 0) { throw new InflateException(" cannot be the root element"); } parseInclude(parser, context, parent, attrs); } else if (TAG_MERGE.equals(name)) { throw new InflateException(" must be the root element"); } else { final View view = createViewFromTag(parent, name, context, attrs); final ViewGroup viewGroup = (ViewGroup) parent; final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs); // 递归调用进行解析,并且将解析出的View添加到其父视图中 rInflateChildren(parser, view, attrs, true); viewGroup.addView(view, params); } } if (finishInflate) { parent.onFinishInflate(); }}
可以看到rInflate中,每次解析到一个View元素就会递归调用,知道该路径下的最后一个元素,然后在回朔回来将每个View元素添加到他们对应的parent中
通过rInflate解析完成以后,整棵View结构树就构建完成了。
关于LayoutInflater加载布局的解析过程到这里就完毕了。
更多相关文章
- ActionBar setDisplayOptions 使用详解
- Android(安卓)通过字符串来获取R下面资源的ID 值
- Android(安卓)3.0 r1中文API文档(103) —— InputMethodManager
- Android(安卓)MediaPlayer研究问题
- Android底部导航栏实现(一)之BottomNavigationBar
- Android中自定义DatePicker
- Android(安卓)动态获取创建与删除文件权限
- php、java、android、ios通用的3des方法(推荐)
- 保存Activity状态