LayoutInfalter布局加载器,在实际的开发中其作用是非常的大的。id通常用来让我们获得布局中控件的id,这个id在R文件中注册。但有时候,相当多的时候,我们需要获得布局文件,那该怎么办呢?
此时,布局加载器就起作用了。Activity类中提供了一个工厂方法getLayoutInflater()来获得LayoutInfalter对象。接下来我们看看LayoutInfalter的inflate()方法的4个重载形式:
1、public View inflate(int resource, ViewGroup root)
2、public View inflate(XmlPullParser parser, ViewGroup root)
3、public View inflate(int resource, ViewGroup root, boolean attachToRoot)
4、public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)
四个方法的参数意义:
int resource 你要加载的布局资源的id,比如R.layout.main_page
ViewGroup root 视图容器类型,是生成的层次结构的可选视图。就是说,你要将布局资源放到的视图容器中。
XmlPullParser parser 剖析器 ,xml DOM 节点包含视图体系的描述
boolean attachToRoot 布尔类型,是说是否将加载的布局资源放到root容器中
我们看看四个方法的Android源码:
public View inflate(int resource, ViewGroup root) {
return inflate(resource, root, root != null);
}
public View inflate(XmlPullParser parser, ViewGroup root) {
return inflate(parser, root, root != null);
}
这两个都调用了另两个重载的方法,因此我们主要看后两个方法。
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();
}
}
DEBUG是LayoutInflater定义的一个私有的最终的布尔型常量,默认值为false
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
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;
}
return result;
}
}
最终返回的是一个View对象,我们可以通过这个对象获得R.layout.main_page中的控件。比如下面的一个自定义适配器类中的一段代码:
public View getView(int position, View itemView, ViewGroup root) {
itemLayout_onload = LayoutInflater.from(context);
itemView=itemLayout_onload.inflate(itemLayoutId, root,false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.item_imageView_user);
TextView textView_name = (TextView) itemView.findViewById(R.id.contactsActivity_textView_name);
TextView textView_number = (TextView) itemView.findViewById(R.id.contactsActivity_textView_contactsTelephone);
imageView.setImageResource(arrayList_contacts.get(position).getImageID());
textView_name.setText(arrayList_contacts.get(position).getName());
textView_number.setText(arrayList_contacts.get(position).getNumber());
return itemView;
}
上面这段代码是一个利用ListView来显示手机中,联系人列表的一个应用中适配器的一段代码。有可能有些开发者会遇到一些问题。(当然上面这段是没问题的)
比如这样itemView=itemLayout_onload.inflate(itemLayoutId, root,true);将最后一个参数设置为true后报错下面的错误:
java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
很显然,是说在添加视图的过程中出错了!很多人不知道到底哪儿出错了。
实际上,我们另外做一个测试应用,新建个样式:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/testLayout"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="111dp"
android:text="Button" />
</RelativeLayout>
通过下面的代码:
//实例化布局加载器
layoutInflater=getLayoutInflater();
//找到主界面的RelativeLayout布局
RelativeLayout re=(RelativeLayout)findViewById(R.id.testLayout);
//进行inflate动态加载
View view=layoutInflater.inflate(R.layout.phone_acitvity_item, re, true);将R.layout.phone_acitvity_item布局加载到relativeLayout容器中发现,并未报错。
其实上面报错的原因不在inflate的参数问题,而在于ListView中不能包含其他控件。细心的人会发现,在ListView中放入控件,直接在布局界面变成灰色,并不可用,会抛出如下异常:
Exception raised during rendering: addView(View, LayoutParams) is not supported in AdapterView
Exception details are logged in Window > Show View > Error Log
有没有发现这儿的报错和前面在LogCat中的错误惊人的相似。错了,不是惊人的相似,其实就是一样的。明白刚才为什么报错了吧!
当然,还有些人会这样写:itemView=itemLayout_onload.inflate(itemLayoutId, null);以为就忽略了ViewGroup,真的是这样吗?
你是否看到了前面两个参数方法的源码:
public View inflate(int resource, ViewGroup root) {
return inflate(resource, root, root != null);
}
实际return inflate(resource, null, false);