Android LayoutInflater深度解析

                           LayoutInflater深度解析

1.概述

对于Inflate的三个参数(int resource, ViewGroup root, boolean attachToRoot),不少人可能有这样的误解:node

  • 若是inflate(layoutId, null )则layoutId的最外层的控件的宽高是没有效果的
  • 若是inflate(layoutId, root, false ) 则认为和上面效果是同样的
  • 若是inflate(layoutId, root, true ) 则认为这样的话layoutId的最外层控件的宽高才能正常显示

是不是真的像这样呢?今天咱们就从源码的角度去探究:android

2.案例 

咱们就采用一个ListView,item为一个按钮app

Activity的布局文件:ide

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mListView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
</ListView>

item的布局文件:布局

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/btn_test"
    android:layout_width="120dp"
    android:layout_height="120dp" >
</Button>

ListView的适配器:测试

/**
 * Created by quguangel on 2016/12/1.
 */

public class MyAdapter extends BaseAdapter {
    private String[] listData;
    private LayoutInflater mInflater;
    public MyAdapter(String[] listData,Context mContext){
        this.listData = listData;
        this.mInflater = LayoutInflater.from(mContext);
    }
    @Override
    public int getCount() {
        return listData.length;
    }

    @Override
    public Object getItem(int i) {
        return listData[i];
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if(view == null){
            view = mInflater.inflate(R.layout.listview_item_layout,null);
            holder = new ViewHolder();
            holder.button = (Button) view.findViewById(R.id.btn_test);
            view.setTag(holder);
        }else{
            holder = (ViewHolder) view.getTag();
        }
        holder.button.setText(listData[i]);
        return view;
    }
    ViewHolder holder;
    static class ViewHolder{
        public Button button;
    }
}

主Activity:this

package qu.com.handlerthread;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;

public class ListViewActivity extends AppCompatActivity {
    private static final String[] datas = {"张三","李四","王五"};
    private ListView mListView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_view);
        mListView = (ListView) findViewById(R.id.mListView);
        mListView.setAdapter(new MyAdapter(datas,this));
    }
}

咱们主要关注getView里面的inflate那行代码:下面我依次把getView里的写成:
一、convertView = mInflater.inflate(R.layout.item, null);
二、convertView = mInflater.inflate(R.layout.item, parent ,false);
三、convertView = mInflater.inflate(R.layout.item, parent ,true);spa

分别看效果图:code

效果图1:convertView = mInflater.inflate(R.layout.listview_item_layout, null);xml

效果图2:convertView = mInflater.inflate(R.layout.listview_item_layout, parent ,false);

咱们如今只经过运行1,2效果图就能够看出,这两种方式加载的布局明显不一样,这与咱们上面的所说的不同。真的是这样吗?等下揭晓。

效果图3:convertView = mInflater.inflate(R.layout.listview_item_layout, parent ,true);

看到第三种状况,你是否是感到特别的惊讶,没错,就是报错了。

从这三幅效果图能够看出,这三种方式加载的布局现实后效果彻底不同。

inflate(R.layout.listview_item_layout, null)的确不能正确处理宽高,可是并不是和

inflate(R.layout.listview_item_layout, parent ,false)显示的效果相同,而它能够完美的显示正确的宽高,

对于inflate(R.layout.listview_item_layout, parent ,true)却报错了,等下咱们源码来分析为啥会报错。

由此可知:咱们前面所说的3个结论明显有错误。

3.源码解析

下面咱们经过源码来解释这三种加载方式的差别

这三个方法,最终都会执行下面的代码:

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {  
       synchronized (mConstructorArgs) {  
           final AttributeSet attrs = Xml.asAttributeSet(parser);  
           Context lastContext = (Context)mConstructorArgs[0];  
           mConstructorArgs[0] = mContext;  
           View result = root;  
  
           try {  
               // Look for the root node.  
               int type;  
               while ((type = parser.next()) != XmlPullParser.START_TAG &&  
                       type != XmlPullParser.END_DOCUMENT) {  
                   // Empty  
               }  
  
               if (type != XmlPullParser.START_TAG) {  
                   throw new InflateException(parser.getPositionDescription()  
                           + ": No start tag found!");  
               }  
  
               final String name = parser.getName();  
                 
               if (DEBUG) {  
                   System.out.println("**************************");  
                   System.out.println("Creating root view: "  
                           + name);  
                   System.out.println("**************************");  
               }  
  
               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, attrs, false);  
               } else {  
                   // Temp is the root view that was found in the xml  
                   View temp;  
                   if (TAG_1995.equals(name)) {  
                       temp = new BlinkLayout(mContext, attrs);  
                   } else {  
                       temp = createViewFromTag(root, name, attrs);  
                   }  
  
                   ViewGroup.LayoutParams params = null;  
  
                   if (root != null) {  
                       if (DEBUG) {  
                           System.out.println("Creating params from root: " +  
                                   root);  
                       }  
                       // Create layout params that match root, if supplied  
                       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);  
                       }  
                   }  
  
                   if (DEBUG) {  
                       System.out.println("-----> start inflating children");  
                   }  
                   // Inflate all children under temp  
                   rInflate(parser, temp, attrs, true);  
                   if (DEBUG) {  
                       System.out.println("-----> done inflating children");  
                   }  
  
                   // We are supposed to attach all the views we found (int temp)  
                   // to root. Do that now.  
                   if (root != null && attachToRoot) {  
                       root.addView(temp, params);  
                   }  
  
                   // Decide whether to return the root that was passed in or the  
                   // top view found in xml.  
                   if (root == null || !attachToRoot) {  
                       result = temp;  
                   }  
               }  
  
           } catch (XmlPullParserException e) {  
               InflateException ex = new InflateException(e.getMessage());  
               ex.initCause(e);  
               throw ex;  
           } catch (IOException e) {  
               InflateException ex = new InflateException(  
                       parser.getPositionDescription()  
                       + ": " + e.getMessage());  
               ex.initCause(e);  
               throw ex;  
           } finally {  
               // Don't retain static reference on context.  
               mConstructorArgs[0] = lastContext;  
               mConstructorArgs[1] = null;  
           }  
  
           return result;  
       }  
   }

1.首先拿到咱们加载XML文件的属性值

2.声明View result = root; 最终值返回result。

View temp;  
                   if (TAG_1995.equals(name)) {  
                       temp = new BlinkLayout(mContext, attrs);  
                   } else {  
                       temp = createViewFromTag(root, name, attrs);  
                   }

在这里咱们建立了View;

if(root!=null)  
{  
 params = root.generateLayoutParams(attrs);  
        if (!attachToRoot)  
 {  
   temp.setLayoutParams(params);  
 }  
}

能够看到,当root不为null,attachToRoot为false时,为temp设置了LayoutParams.

继续往下看:

if (root != null && attachToRoot)  
{  
root.addView(temp, params);  
}

能够看到,当root不为null,attachToRoot为true时,将temp按照params添加到root中

if (root == null || !attachToRoot) {   
result = temp;   
}

能够看到,当root为null,直接将temp赋值给result;最后返回result。

从上面的分析已经能够看出:

Inflate(resId , null ) 只建立temp ,返回temp

Inflate(resId , parent, false )建立temp,而后执行temp.setLayoutParams(params);返回temp

Inflate(resId , parent, true ) 建立temp,而后执行root.addView(temp, params);最后返回root

由上面已经可以解释:

Inflate(resId , null )不能正确处理宽和高是由于:layout_width,layout_height是相对了父级设置的,必须与父级的LayoutParams一致。而此temp的getLayoutParams为null

Inflate(resId , parent,false ) 能够正确处理,由于temp.setLayoutParams(params);这个params正是root.generateLayoutParams(attrs);获得的。

Inflate(resId , parent,true )不只可以正确的处理,并且已经把resId这个view加入到了parent,而且返回的是parent,和以上二者返回值有绝对的区别,还记得文章前面的例子上,MyAdapter里面的getView报的错误: 

这是由于源码中调用了root.addView(temp, params);而此时的root是咱们的ListView,ListView为AdapterView的子类:
直接看AdapterView的源码:

@Override  
  public void addView(View child) {  
        throw new UnsupportedOperationException("addView(View) is not supported in AdapterView");  
  }

看到这里就能解决我以前出现的异常呢。

4.进一步探究

主Activity的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mTextView"
    android:layout_width="120dp"
    android:layout_height="120dp"
    android:text="测试"
    android:textSize="30sp"
    android:gravity="center"
   >
</TextView>

主Activity:

public class ListViewActivity extends AppCompatActivity {
    private LayoutInflater mInflater;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_view);
        mInflater = LayoutInflater.from(this);

        View testView1 = mInflater.inflate(R.layout.activity_list_view,null);

        View testView2 = mInflater.inflate(R.layout.activity_list_view,
                (ViewGroup)findViewById(android.R.id.content),false);

        View testView3 = mInflater.inflate(R.layout.activity_list_view,
                (ViewGroup)findViewById(android.R.id.content),true);

        Log.e("le","testView1="+testView1 +"testView1.layoutParams="+testView1.getLayoutParams());
        Log.e("le","testView2="+testView1 +"testView2.layoutParams="+testView2.getLayoutParams());
        Log.e("le","testView3="+testView1 +"testView3.layoutParams="+testView3.getLayoutParams());
    }
}

能够看到咱们的主Activity并无执行setContentView,仅仅执行了LayoutInflater的3个方法。
注:parent咱们用的是Activity的内容区域:即android.R.id.content,是一个FrameLayout,咱们在setContentView(resId)时,其实系统会自动为了包上一层FrameLayout(id=content)。

按照咱们上面的说法:

view1的layoutParams 应该为null
view2的layoutParams 应该不为null,且为FrameLayout.LayoutParams
view3为FrameLayout,且将这个button添加到Activity的内容区域了(由于R.id.content表明Actvity内容区域)

下面看一下输出结果,和Activity的展现:

可见,虽然咱们没有执行setContentView,可是依然能够看到绘制的控件,是由于

View testView3 = mInflater.inflate(R.layout.activity_list_view,
                (ViewGroup)findViewById(android.R.id.content),true)

这个方法内部已经执行了root.addView(temp , params); 上面已经解析过了。

也能够看出:和咱们的推测彻底一致,到此已经彻底说明了inflate3个重载的方法的区别。相信你们之后在使用时也能选择出最好的方式。不过下面准备从ViewGroup和View的角度来讲一下,为啥layoutParams为null,就不能这确的处理。

5.从ViewGroup和View的角度来解析

若是你们对自定义ViewGroup和自定义View有必定的掌握,确定不会对onMeasure方法陌生:
ViewGroup的onMeasure方法所作的是:

为childView设置测量模式和测量出来的值。

如何设置呢?就是根据LayoutParams。
若是childView的宽为:LayoutParams. MATCH_PARENT,则设置模式为MeasureSpec.EXACTLY,且为childView计算宽度。
若是childView的宽为:固定值(即大于0),则设置模式为MeasureSpec.EXACTLY,且将lp.width直接做为childView的宽度。
若是childView的宽为:LayoutParams. WRAP_CONTENT,则设置模式为:MeasureSpec.AT_MOST
高度与宽度相似。

View的onMeasure方法:
主要作的就是根据ViewGroup传入的测量模式和测量值,计算本身应该的宽和高:
通常是这样的流程:
若是宽的模式是AT_MOST:则本身计算宽的值。
若是宽的模式是EXACTLY:则直接使用MeasureSpec.getSize(widthMeasureSpec);

对于最后一块,若是不清楚,没关系,之后我会在自定义ViewGroup和自定义View时详细讲解的。

大概就是这样的流程,真正的绘制过程确定比这个要复杂,就是为了说明若是View的宽和高若是设置为准确值,则必定依赖于LayoutParams,因此咱们的inflate(resId,null)才没能正确处理宽和高。

相关文章
相关标签/搜索