LayoutInflater 的正确用法和原理

LayoutInflater 用的比较多,常见的是listview,listview的适配器 ada 中getView()方法,和listview的    public void addHeaderView(View v) 方法。

LayoutInflater中常用的方法

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        if (DEBUG) {
            Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
                    + Integer.toHexString(resource) + ")");
        }

        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

这两个方法都可以吧layout转换为View,这里就又引出一个方法,View 类中的一个静态布局转化方法

View
 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
    }
我们会发现,也是调用了 LayoutInflater的方法。
最终都是调用了

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

            final Context inflaterContext = mContext;
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context) mConstructorArgs[0];
            mConstructorArgs[0] = inflaterContext;
            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, inflaterContext, attrs, false);
                } else {
                    // Temp is the root view that was found in the xml
                    final View temp = createViewFromTag(root, name, inflaterContext, 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 against its context.
                    rInflateChildren(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 (Exception 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;
        }
    }

listview中,一不小心,就会发现item的宽度和高度不太正确。比如说
item 布局

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

在适配器 ada 的getView方法中

1、convertView = mInflater.inflate(R.layout.item, null);
2、convertView = mInflater.inflate(R.layout.item, parent ,false);
3、convertView = mInflater.inflate(R.layout.item, parent ,true);

会发现
第一种 会显示listview,但宽度和高度显示错误
第二一种 会显示listview,宽度和高度显示正确
第一种 不会显示listview,直接报错。

为什么呢,看看最后调用的方法的代码,inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)

看最后,最终返回值为result, result = root ,root是上面传进来的

方法中间 创建了View  temp = createViewFromTag(root, name, attrs);
    if(root!=null)  
    {  
     params = root.generateLayoutParams(attrs);  
            if (!attachToRoot)  
     {  
       temp.setLayoutParams(params);  
     }  
    }  
当root不为null,attachToRoot为false时,为temp设置了LayoutParams. 这个params是 AbsListView.LayoutParams(getContext(), attrs),获取到应该是item的参数设置。

    if (root != null && attachToRoot)  
    {  
    root.addView(temp, params);  
    }  
root不为null,attachToRoot为true时,把tmp按照params添加到root中。
listview的addView方法不能用,直接报错,


    if (root == null || !attachToRoot) {   
    result = temp;   
    }   
root为null,或者attachToRoot为false则,把temp赋值给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

因此,想让listview中item的宽度和高度正常显示,两个方法
一  使用 Inflate(resId , parent, false )方法;
二  在item的跟布局上在加上一层布局,相对布局或线性布局都行,
android:layout_width="match_parent"
    android:layout_height="match_parent"

相对来说,方法一简单,并且效率高,节省内存消耗。




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值