ListView--1 之 LayoutInfLayout源码分析

LayoutInflater 布局填充器,用来将指定xml资源文件加载到View视图对象中。
在ListView,GridView等AdapterView适配器控件填充数据时,此时就使用到了LayoutInflater加载布局文件.

先看一下 最常见的使用

点击查看获取填充器 LayoutInflater.from(mContext) 的源码,

/**
     * Obtains the LayoutInflater from the given context.
     */
    public static LayoutInflater from(Context context) {
        LayoutInflater LayoutInflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (LayoutInflater == null) {
            throw new AssertionError("LayoutInflater not found.");
        }
        return LayoutInflater;
    }

需要根据当前上下文Context获取LayoutInflater 对象,所以inflater是跟当前显示页面相关联,确保可以正确的匹配当前正在运行的设备
根据源码 我们获取LayoutInflater对象也可以使用以下这种写法:
 LayoutInflater LayoutInflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

根据文档提示,还有几种快速获得LayoutInflater对象的写法,仅供参考
Activity currentActivity = (Activity) mContext;
LayoutInflater inflater = currentActivity.getLayoutInflater();
inflater = currentActivity.getWindow().getLayoutInflater();


接下来就是我们熟悉的 inflate方法加载指定xml文件,观察源码中 inflate有如下四个重载方法,用的比较多是第1和第3,


// 使用LayoutInflater
  convertView = inflater.inflate(R.layout.item_listadapter, null);
  convertView = inflater .inflate(R.layout.item_listadapter, parent, false);
 加载指定xml资源文件 到view 对象中 ,相信不少同学和我一样使用了很长时间,觉得这两个方法作用一样,往往图省事,还会优先使用两个参数的方法,所以很久以后自己的Android水平还停留在仅仅会用,却不清楚为什么的水平,所以干了两年感觉提升不大,以后还得多研究一下Android系统的原理,下面就进入源码角度分析一下吧

/**
     * Inflate a new view hierarchy from the specified xml resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param 用来加载的 xml布局资源文件编号,如:
     * <code>R.layout.main_page</code>)

     * @param root 可选择的生成视图的父级视图,如果提供了则作为xml生成视图的根视图
     * @return The root View of the inflated hierarchy. If root was supplied,
     * this is the root View; otherwise it is the root of the inflated
     * XML file.
     */
    public View inflate(int resource, ViewGroup root) {
        return inflate(resource, root, root != null);
    }


而 public View inflate(int resource, ViewGroup root)  内部也是调用了inflate(int resource, ViewGroup root, boolean attachToRoot)方法,三个参数分别是 

1、xml布局文件的资源Id;

2、有xml生成view的父级视图

3、是否加载父级视图的参数,此参数很重要,如果为false则只是用子视图的LayoutParams来创建根视图的XML

进入该方法我们可以看到 getContext().getResources().getLayout(resource) 把指定xml资源文件加载到 XmlResourceParser 解析器中,由此可以推断,inflater方法是通过xml解析
/**
     * Inflate a new view hierarchy from the specified xml resource. Throws
     * {@link InflateException} if there is an error.
     * 
     * @param resource ID for an XML layout resource to load (e.g.,
     *        <code>R.layout.main_page</code>)
     * @param root Optional view to be the parent of the generated hierarchy (if
     *        <em>attachToRoot</em> is true), or else simply an object that
     *        provides a set of LayoutParams values for root of the returned
     *        hierarchy (if <em>attachToRoot</em> is false.)
     * @param attachToRoot Whether the inflated hierarchy should be attached to
     *        the root parameter? If false, root is only used to create the
     *        correct subclass of LayoutParams for the root view in the XML.
     * @return The root View of the inflated hierarchy. If root was supplied and
     *         attachToRoot is true, this is root; otherwise it is the root of
     *         the inflated XML file.
     */
    public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
        if (DEBUG) System.out.println("INFLATING from resource: " + resource);
        XmlResourceParser parser = getContext().getResources().getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

点击继续查看inflate调用,这次终于可以看到inflate方法的庐山真面目,inflate不管以调用哪个方法,最终都是调用到了下面这个

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) 


进入方法第一行,首先是从XmlResourceParser  对象获得xml文件的属性集

final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context)mConstructorArgs[0];
mConstructorArgs[0] = mContext;
View result = root;

接下来重点看一下,XML解析,可以从代码中知道此处采用的是Pull对xml进行解析,解析判断的几个成员变量内容如下:
private static final String TAG_MERGE = "merge";
private static final String TAG_INCLUDE = "include";
private static final String TAG_1995 = "blink";
private static final String TAG_REQUEST_FOCUS = "requestFocus";
回到源码中,着重看以下几行代码,先获取xml元素的名称

final String name = parser.getName();
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);
                }
看第一个if块  TAG_MERGE=merge,而我们的布局文件中并未包含这个元素,由此可转入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);
                    }


TAG_1995=blink ,布局中也没有这个元素,所以 temp = createViewFromTag(root, name, attrs);


接着往下看:使我们的本文最重点分析的

if (root != null) {
    if (DEBUG) {
        System.out.println("Creating params from root: " +
                root);
    }
    // <span style="color:#ff6600;">Create layout params that match root, if supplied,此处根据布局文件的属性集获取到xml根节点的LayoutParams</span>
    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);
    }
}
首先判断 root!=null,根视图是否为空,不为空则获取根节点的LayoutParams,然后判断 attachToRoot,如果为false, 生成视图则设置根节点中获得的LayoutParams。

此时我们在回顾一下,开始的两种调用方式

convertView = inflater.inflate(R.layout.item_listadapter, null); // 方式一:root=null,
convertView = inflater .inflate(R.layout.item_listadapter, parent, false);// root=parent,attachToRoot=false

方式一中又调用方式二,
public View inflate(int resource, ViewGroup root) {
        return inflate(resource, root, root != null);
    }



进入第二个调用函数此时:

方式一中 : root = null,  attachToRoot = false

方式二中:root = parent, attachToRoot=false

两种方式以不同的 root值进入到第三个函数

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)

此时在于区别
判断 root!=null,根视图是否为空,不为空则获取根节点的LayoutParams;然后判断 attachToRoot,如果为false, 生成视图则设置根节点中获得的LayoutParams;所以采用两个参数的inflate调用方式是不会进入到这一步,也就是说根视图设置的属性也不起作用了,所以该方法今后慎用,有限使用三个参数的inflate方法
public View inflate(int resource, ViewGroup root, boolean attachToRoot)

上述就是一个从源码角度粗略分析的结果,下面我们通过代码方式来看看实际运行效果

if (isThreeParam) {
	convertView = inflater
			.inflate(R.layout.item, parent, false);
} else {
	convertView = inflater.inflate(R.layout.item, null);
}


item布局如下:我在根布局中设置了高度为80dp,居中属性
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:gravity="center"
    android:orientation="vertical">
    
	<TextView android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="这是一条测试数据哦!!!"/>
</LinearLayout>




两种方法加载同一个页面,效果区别很明显,调用了两个参数的inflate忽略了根节点的高度,而三个参数的根节点却很好的按照根节点参数现实了出来。但同样我设置居中属性,两个页面的都显示了出来,回过头再看源码generateLayoutParams,生成params参数是只和根节点的高度和有关

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);
                        }
                    }
public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new LayoutParams(getContext(), attrs);
    }

public LayoutParams(Context c, AttributeSet attrs) {
            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout);
            setBaseAttributes(a,
                    R.styleable.ViewGroup_Layout_layout_width,
                    R.styleable.ViewGroup_Layout_layout_height);
            a.recycle();
        }


总结:

两种方法加载同一个页面,效果区别很明显,调用了两个参数的inflate忽略了根节点的高度,而三个参数的根节点却很好的按照根节点宽度和高度参数显示了出来


demo代码下载地址

第一次写源码,分析的比较浅,写的也有点乱,学习继续...





两种方法加载同一个页面,效果区别很明显,调用了两个参数的inflate忽略了根节点的高度,而三个参数的根节点却很好的按照根节点参数现实了出来
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值