LayoutInflater使用与解析

LayoutInflater

与findViewById()区别

LayoutInflater:用来找res/layout/下的xml布局文件,并且实例化

​ 对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入

findViewById():找xml布局文件下的具体widget控件(如Button、TextView等)

​ 对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素

实例化方法

//public abstract class LayoutInflater extends Object	
//调用关系:1调用2,2调用3
1、LayoutInflater inflater = activity.getLayoutInflater();	
2、LayoutInflater inflater = LayoutInflater.from(context);  
2、LayoutInflater inflater =  (LayoutInflater)context.getSystemService
                             	 (Context.LAYOUT_INFLATER_SERVICE);

inflate()

//重载方法
public View inflate (int resource, ViewGroup root) 
public View inflate (XmlPullParser parser, ViewGroup root)
public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)  
public View inflate (int resource, ViewGroup root, boolean attachToRoot)
//示例
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);       
View view = inflater.inflate(R.layout.custom, (ViewGroup)findViewById(R.id.test)); 
//参数:ViewGroup可为null
EditText editText = (EditText)view.findViewById(R.id.content);

ViewGroup参数

final AttributeSet attrs = Xml.asAttributeSet(parser);//从Xml中取出传入的布局文件的属性attrs
...
    <span style="white-space:pre">	</span>    View result = root;		//默认root为返回值
...
    // Temp is the root view that was found in the xml
    //temp是通过xml生成的view的根视图
    final View temp = createViewFromTag(root, name, attrs, false);	

	ViewGroup.LayoutParams params = null;
...
    // Inflate all children under temp
    // 循环inflate temp的子视图(此时的temp为不包含LayoutParams的View)
    rInflate(parser, temp, attrs, true, true);
...
    if (root != null) {	//当root不为null
        if (DEBUG) {
            System.out.println("Creating params from root: " +
                               root);
        }
        // Create layout params that match root, if supplied
        params = root.generateLayoutParams(attrs);

        //若attachToRoot为false,则将通过attires生成的bu布局参数params设为temp的内部布局参数变量mLayoutParams
        if (!attachToRoot) {
            // Set the layout params for temp if we are not
            // attaching. (If we are, we use addView, below)
            temp.setLayoutParams(params);	
        }
    }
...
    // 若root不为空且attachToRoot为true,则temp贴到root上(连带temp的布局属性)
    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.
// 若root为空或者attachToRoot为false,则返回值为temp
if (root == null || !attachToRoot) {
    result = temp;
}
...
    return result;

temp是利用xml文件解析出的attrs创造出来的一个View

ViewGroup.LayoutParams:包含了布局View的宽和高的属性,如设置此属性,则将控件的宽高属性表现出来

root == null,则返回temp(未设定其mLayoutParams)

root != null,且attachToRoot==true,则返回添加了temp(已设定过其mLayoutParams)的root视图

root != null,且attachToRoot==false,则返回temp(未设定其mLayoutParams)

你可能感兴趣的:(Android,Android基础)