Android LayoutInflater詳解

前言

LayoutInflater,相信我們都不會陌生,在ListView裏的getView方法裏,我們都會使用,今天我們就來詳細的分析下LayoutInflater的inflate方法,方便以後的工作中選擇最適合的方法。


基本使用

LayoutInflater有以下三個方式,它們有什麼不同呢,在我初學的時候,還真不清楚。

inflate(resource, null);
inflate(resource, parent, false);
inflate(resource, parent, true);

那麼這三種方式有什麼不同呢?我們用實踐來說明

activity_main.xml

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_lv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

</ListView>

item.xml

<Button xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:id="@+id/item_btn"  
    android:layout_width="100dp"  
    android:layout_height="100dp" >  
</Button>  

MainAdapter.java

public class MainAdapter extends BaseAdapter  
{  

    private LayoutInflater mInflater;  
    private List<String> mDatas;  

    public MainAdapter(Context context, List<String> datas)  
    {  
        mInflater = LayoutInflater.from(context);  
        mDatas = datas;  
    }  

    @Override  
    public int getCount()  
    {  
        return mDatas.size();  
    }  

    @Override  
    public Object getItem(int position)  
    {  
        return mDatas.get(position);  
    }  

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

    @Override  
    public View getView(int position, View convertView, ViewGroup parent)  
    {  

        ViewHolder holder = null;  
        if (convertView == null)  
        {  
            holder = new ViewHolder();  
            convertView = mInflater.inflate(R.layout.item, null);  
//          convertView = mInflater.inflate(R.layout.item, parent ,false);  
//          convertView = mInflater.inflate(R.layout.item, parent ,true);  
            holder.mBtn = (Button) convertView.findViewById(R.id.item_btn);  
            convertView.setTag(holder);  
        } else  
        {  
            holder = (ViewHolder) convertView.getTag();  
        }  

        holder.mBtn.setText(mDatas.get(position));  

        return convertView;  
    }  

    private final class ViewHolder  
    {  
        Button mBtn;  
    }  
}  

MainActivity.java

public class MainActivity extends Activity {

    private ListView mListView;
    private MainAdapter mAdapter;
    private List<String> mDatas = Arrays.asList("I", "Love", "Android");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = (ListView) findViewById(R.id.main_lv);
        mAdapter = new MainAdapter(this, mDatas);
        mListView.setAdapter(mAdapter);
    }

}

我們關注的就是getView裏的三個方法:

           convertView = mInflater.inflate(R.layout.item, null);  
//          convertView = mInflater.inflate(R.layout.item, parent ,false);  
//          convertView = mInflater.inflate(R.layout.item, parent ,true); 

分別運行,看看效果:

第一個:這裏寫圖片描述

第二個:這裏寫圖片描述

第三個:這裏寫圖片描述

Logcat:

Caused by: java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView

我們發現,第一個inflater(R.layout.item, null )不能正確的處理寬和高的值,而inflate(R.layout.item, parent ,false); 可以正確處理寬和高的值。至於第三個,則會報錯。。。。下面我們就來從源碼的角度來分析,第三個爲什麼會報錯?


源碼分析

我們看這三種形式都會進入的inflate方法:

 public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");

            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;
            }

            Trace.traceEnd(Trace.TRACE_TAG_VIEW);

            return result;
        }
    }

這裏把我們關注的代碼提出來:

View result = root;

inflate(resId , null);

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

inflate(resId , root, false);

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);
                        }
                    }

inflate(resId , root, true);

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

同過上述代碼,我們發現:
Inflate(resId , null ) 只創建temp ,返回temp
Inflate(resId , root, false )創建temp,然後執行 temp.setLayoutParams(params);返回temp
Inflate(resId , root, 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報的錯誤:

Caused by: java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView

原因是調用了addView方法,而ListView是AdapterView的子類,在AdapterView裏面有這麼一段代碼:

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

現在我們清楚爲什麼會報錯了。。。。


思考

既然第三種方式會默認調用addView方法,那麼我們在Activity裏寫如下代碼會是怎樣?:

MainActivity.java

View view = LayoutInflater.from(this).inflate(R.layout.activity_main,  
                (ViewGroup)findViewById(android.R.id.content), true); 

activity_main.xml

<Button xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/item_btn"
    android:layout_width="100dp"
    android:layout_height="100dp" >

</Button>

我們運行一下看看效果:
這裏寫圖片描述

是的,雖然我們沒有執行setContentView,但是依然可以看到繪製的控件,是因爲
View view= mInflater.inflate(R.layout.activity_main,(ViewGroup)findViewById(android.R.id.content), true);
這個方法內部已經執行了root.addView(temp , params);

這樣,以後我們在使用LayoutInflater時就可以選擇最適合的方式了。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章