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);