Android XML布局与View之间的转换

本文深入探讨了Android中如何将XML布局文件转换为View组件的过程。从setContentView方法入手,逐步剖析了PhoneWindow、LayoutInflater和XmlPullParser的角色与工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android的布局方式有两种,一种是通过xml布局,一种是通过java代码布局,两种布局方式各有各的好处,当然也可以相互混合使用。很多人都习惯用xml布局,那xml布局是如何转换成view的呢?本文从源码的角度来简单分析下整个过程。

首先,创建一个新的项目,默认生成一个activity,其中xml布局很简单,就一个RelativeLayout套了一个ImageView,代码及效果如下:

  1. public class MainActivity extends Activity {  
  2.     @Override  
  3.     protected void onCreate(Bundle savedInstanceState) {  
  4.         super.onCreate(savedInstanceState);  
  5.         setContentView(R.layout.activity_main);  
  6.     }  
  7. }  

其中关键之处就在于调用了父类Activity的setContentView方法:

  1. /**  
  2.  * Set the activity content from a layout resource.  The resource will be  
  3.  * inflated, adding all top-level views to the activity.  
  4.  *   
  5.  * @param layoutResID Resource ID to be inflated.  
  6.  */  
  7. public void setContentView(int layoutResID) {  
  8.     getWindow().setContentView(layoutResID);  
  9. }  

getWindow返回的是PhoneWindow实例,那我们直接来看PhoneWindow中的setContentView方法:

  1. @Override  
  2. public void setContentView(int layoutResID) {  
  3.     if (mContentParent == null) {  
  4.         installDecor();  
  5.     } else {  
  6.         mContentParent.removeAllViews();  
  7.     }  
  8.     mLayoutInflater.inflate(layoutResID, mContentParent);  
  9.     final Callback cb = getCallback();  
  10.     if (cb != null) {  
  11.         cb.onContentChanged();  
  12.     }  
  13. }  

我们知道每个activity实际都对应一个PhoneWindow,拥有一个顶层的DecorView,DecorView继承自FrameLayout,作为根View,其中包含了一个标题区域和内容区域,这里的mContentParent就是其内容区域。关于PhoneWindow和DecorView的具体内容,读者可自行查阅。这段代码的意思很简单,如果DecorView的内容区域为null,就先初始化,否则就先把内容区域的子View全部移除,最后再引入layout布局,所以,关键在于mLayoutInflater.inflate(layoutResID, mContentParent); 代码继续往下看:
  1. public View inflate(int resource, ViewGroup root) {  
  2.     return inflate(resource, root, root != null);  
  3. }  
  1. public View inflate(int resource, ViewGroup root, boolean attachToRoot) {  
  2.     if (DEBUG) System.out.println("INFLATING from resource: " + resource);  
  3.     XmlResourceParser parser = getContext().getResources().getLayout(resource);  
  4.     try {  
  5.         return inflate(parser, root, attachToRoot);  
  6.     } finally {  
  7.         parser.close();  
  8.     }  
  9. }  

这里首先根据layout布局文件的Id生成xml资源解析器,然后再调用inflate(parser, root, attachToRoot)生成具体的view。XmlResourceParser是继承自XmlPullParser和AttributeSet的接口,这里的parser其实是XmlBlock的内部类Parser的实例。
  1. public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {  
  2.         synchronized (mConstructorArgs) {  
  3.             final AttributeSet attrs = Xml.asAttributeSet(parser);  
  4.             Context lastContext = (Context)mConstructorArgs[0];  
  5.             mConstructorArgs[0] = mContext;  
  6.             View result = root;  
  7.   
  8.             try {  
  9.                 // Look for the root node.  
  10.                 int type;  
  11.                 while ((type = parser.next()) != XmlPullParser.START_TAG &&  
  12.                         type != XmlPullParser.END_DOCUMENT) {  
  13.                     // Empty  
  14.                 }  
  15.   
  16.                 if (type != XmlPullParser.START_TAG) {  
  17.                     throw new InflateException(parser.getPositionDescription()  
  18.                             + ": No start tag found!");  
  19.                 }  
  20.   
  21.                 final String name = parser.getName();  
  22.                   
  23.                 if (DEBUG) {  
  24.                     System.out.println("**************************");  
  25.                     System.out.println("Creating root view: "  
  26.                             + name);  
  27.                     System.out.println("**************************");  
  28.                 }  
  29.   
  30.                 if (TAG_MERGE.equals(name)) {  
  31.                     if (root == null || !attachToRoot) {  
  32.                         throw new InflateException("<merge /> can be used only with a valid "  
  33.                                 + "ViewGroup root and attachToRoot=true");  
  34.                     }  
  35.   
  36.                     rInflate(parser, root, attrs);  
  37.                 } else {  
  38.                     // Temp is the root view that was found in the xml  
  39.                     View temp = createViewFromTag(name, attrs);  
  40.   
  41.                     ViewGroup.LayoutParams params = null;  
  42.   
  43.                     if (root != null) {  
  44.                         if (DEBUG) {  
  45.                             System.out.println("Creating params from root: " +  
  46.                                     root);  
  47.                         }  
  48.                         // Create layout params that match root, if supplied  
  49.                         params = root.generateLayoutParams(attrs);  
  50.                         if (!attachToRoot) {  
  51.                             // Set the layout params for temp if we are not  
  52.                             // attaching. (If we are, we use addView, below)  
  53.                             temp.setLayoutParams(params);  
  54.                         }  
  55.                     }  
  56.   
  57.                     if (DEBUG) {  
  58.                         System.out.println("-----> start inflating children");  
  59.                     }  
  60.                     // Inflate all children under temp  
  61.                     rInflate(parser, temp, attrs);  
  62.                     if (DEBUG) {  
  63.                         System.out.println("-----> done inflating children");  
  64.                     }  
  65.   
  66.                     // We are supposed to attach all the views we found (int temp)  
  67.                     // to root. Do that now.  
  68.                     if (root != null && attachToRoot) {  
  69.                         root.addView(temp, params);  
  70.                     }  
  71.   
  72.                     // Decide whether to return the root that was passed in or the  
  73.                     // top view found in xml.  
  74.                     if (root == null || !attachToRoot) {  
  75.                         result = temp;  
  76.                     }  
  77.                 }  
  78.   
  79.             } catch (XmlPullParserException e) {  
  80.                 InflateException ex = new InflateException(e.getMessage());  
  81.                 ex.initCause(e);  
  82.                 throw ex;  
  83.             } catch (IOException e) {  
  84.                 InflateException ex = new InflateException(  
  85.                         parser.getPositionDescription()  
  86.                         + ": " + e.getMessage());  
  87.                 ex.initCause(e);  
  88.                 throw ex;  
  89.             } finally {  
  90.                 // Don't retain static reference on context.  
  91.                 mConstructorArgs[0] = lastContext;  
  92.                 mConstructorArgs[1] = null;  
  93.             }  
  94.   
  95.             return result;  
  96.         }  
  97.     }  

第21行,获取xml根节点名:

  1. final String name = parser.getName();  

第39行根据节点名创建临时View(temp),这个临时view(temp)也是xml布局的根view:

  1. View temp = createViewFromTag(name, attrs);  

第61行,在临时view(temp)的节点下创建所有子View,显然这个方法里是通过遍历xml所有子view节点,调用createViewFromTag方法生成子view并加载到根view中:
  1. rInflate(parser, temp, attrs);  

第68到76行,则是判断,如果inflate方法有父view,则把临时view(temp)加载到父view中再返回,如果没有,则直接返回临时view(temp),我们这里调用inflate方法的时候显然有父view,即mContentParent,也就是最顶层view DecorView的内容区域。这里最关键有两个方法,一个是createViewFromTag,另一个是rInflate,现在来逐一分析:createViewFromTag实际最终调用的是createView方法:
  1. public final View createView(String name, String prefix, AttributeSet attrs)  
  2.             throws ClassNotFoundException, InflateException {  
  3.         Constructor constructor = sConstructorMap.get(name);  
  4.         Class clazz = null;  
  5.   
  6.         try {  
  7.             if (constructor == null) {  
  8.                 // Class not found in the cache, see if it's real, and try to add it  
  9.                 clazz = mContext.getClassLoader().loadClass(  
  10.                         prefix != null ? (prefix + name) : name);  
  11.                   
  12.                 if (mFilter != null && clazz != null) {  
  13.                     boolean allowed = mFilter.onLoadClass(clazz);  
  14.                     if (!allowed) {  
  15.                         failNotAllowed(name, prefix, attrs);  
  16.                     }  
  17.                 }  
  18.                 constructor = clazz.getConstructor(mConstructorSignature);  
  19.                 sConstructorMap.put(name, constructor);  
  20.             } else {  
  21.                 // If we have a filter, apply it to cached constructor  
  22.                 if (mFilter != null) {  
  23.                     // Have we seen this name before?  
  24.                     Boolean allowedState = mFilterMap.get(name);  
  25.                     if (allowedState == null) {  
  26.                         // New class -- remember whether it is allowed  
  27.                         clazz = mContext.getClassLoader().loadClass(  
  28.                                 prefix != null ? (prefix + name) : name);  
  29.                           
  30.                         boolean allowed = clazz != null && mFilter.onLoadClass(clazz);  
  31.                         mFilterMap.put(name, allowed);  
  32.                         if (!allowed) {  
  33.                             failNotAllowed(name, prefix, attrs);  
  34.                         }  
  35.                     } else if (allowedState.equals(Boolean.FALSE)) {  
  36.                         failNotAllowed(name, prefix, attrs);  
  37.                     }  
  38.                 }  
  39.             }  
  40.   
  41.             Object[] args = mConstructorArgs;  
  42.             args[1] = attrs;  
  43.             return (View) constructor.newInstance(args);  
  44.   
  45.         } catch (NoSuchMethodException e) {  
  46.             InflateException ie = new InflateException(attrs.getPositionDescription()  
  47.                     + ": Error inflating class "  
  48.                     + (prefix != null ? (prefix + name) : name));  
  49.             ie.initCause(e);  
  50.             throw ie;  
  51.   
  52.         } catch (ClassNotFoundException e) {  
  53.             // If loadClass fails, we should propagate the exception.  
  54.             throw e;  
  55.         } catch (Exception e) {  
  56.             InflateException ie = new InflateException(attrs.getPositionDescription()  
  57.                     + ": Error inflating class "  
  58.                     + (clazz == null ? "<unknown>" : clazz.getName()));  
  59.             ie.initCause(e);  
  60.             throw ie;  
  61.         }  
  62.     }  

其实这个方法很简单,就是通过xml节点名,通过反射获取view的实例再返回,其中先去map中查询构造函数是否存在,如果存在则直接根据构造函数创建实例,这样做的好处是不用每次都通过class去获取构造函数再创建实例,我们看第18通过类实例获取构造函数:

constructor = clazz.getConstructor(mConstructorSignature);

其中mConstructorSignature定义如下:

  1. private static final Class[] mConstructorSignature = new Class[] {  
  2.         Context.class, AttributeSet.class};  

很显然,这里用的是带有Context和AttributeSet两个参数的构造函数,这也就是为什么,自定义view一定要重载这个构造函数的原因。最后就是rInflate方法:

  1. <pre name="code" class="html">private void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs)  
  2.             throws XmlPullParserException, IOException {  
  3.   
  4.         final int depth = parser.getDepth();  
  5.         int type;  
  6.   
  7.         while (((type = parser.next()) != XmlPullParser.END_TAG ||  
  8.                 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {  
  9.   
  10.             if (type != XmlPullParser.START_TAG) {  
  11.                 continue;  
  12.             }  
  13.   
  14.             final String name = parser.getName();  
  15.               
  16.             if (TAG_REQUEST_FOCUS.equals(name)) {  
  17.                 parseRequestFocus(parser, parent);  
  18.             } else if (TAG_INCLUDE.equals(name)) {  
  19.                 if (parser.getDepth() == 0) {  
  20.                     throw new InflateException("<include /> cannot be the root element");  
  21.                 }  
  22.                 parseInclude(parser, parent, attrs);  
  23.             } else if (TAG_MERGE.equals(name)) {  
  24.                 throw new InflateException("<merge /> must be the root element");  
  25.             } else {  
  26.                 final View view = createViewFromTag(name, attrs);  
  27.                 final ViewGroup viewGroup = (ViewGroup) parent;  
  28.                 final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);  
  29.                 rInflate(parser, view, attrs);  
  30.                 viewGroup.addView(view, params);  
  31.             }  
  32.         }  
  33.   
  34.         parent.onFinishInflate();  
  35.     }  
实这个方法也很简单,就是通过parser解析xml节点再生成对应View的过程。

XML转换成View的过程就是这样了,如有错误之处,还望指正,回到本文开头,其实我们还可以这样写:

  1. @Override  
  2. protected void onCreate(Bundle savedInstanceState) {  
  3.     super.onCreate(savedInstanceState);  
  4.     View content = LayoutInflater.from(this).inflate(R.layout.activity_main, null);  
  5.     setContentView(content);  
  6. }  


大家发现问题没,相较于本文开头的写法,后面的灰色布局变成全屏了,我们来看看xml代码:

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="300dip"  
  4.     android:layout_height="300dip"  
  5.     android:background="#888888"  
  6.     tools:context=".MainActivity" >  
  7.   
  8.     <ImageView  
  9.         android:layout_width="200dip"  
  10.         android:layout_height="200dip"  
  11.         android:background="#238712"  
  12.         android:contentDescription="@null" />  
  13.   
  14. </RelativeLayout>  

我明明设置了RelativeLayout的宽度和高度分别为300dip,但为什么全屏了?这是因为layout_width和layout_height是相对于父布局而言的,我们这里inflate的时候设置的父布局为null,所以这个属性设置也就无效了,我们加一个父布局再试试:

  1. @Override  
  2. protected void onCreate(Bundle savedInstanceState) {  
  3.     super.onCreate(savedInstanceState);  
  4.     RelativeLayout rootView = new RelativeLayout(this);  
  5.     View content = LayoutInflater.from(this).inflate(R.layout.activity_main, rootView);  
  6.     setContentView(content);  
  7. }  


OK,我们白色的背景又有了~



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值