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时就可以选择最适合的方式了。。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值