Android - LayoutInflater 的使用

LayoutInflater is used to instantiate layout XML file into its corresponding View objects. It is never be used directly -- use getLayoutInflater()or getSystemService(String) to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on.
也就是說我們用LayoutInflater做一件事:inflate。inflate這個方法總共有四種形式,目的都是把xml表述的layout轉化爲View。
For example:
LayoutInflater inflater = (LayoutInflater)>context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
1. Context.public abstract Object getSystemService (String name) Return the handle to a system-level service by name. The class of the returned object varies by the requested name

2. 有2種獲得LayoutInflater的方法
(1)通過SystemService獲得
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

(2)從給定的contex獲取

protected LayoutInflater (Context  context)


(3)二者區別:實質是一樣的,請看源碼
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;
}

3. findViewById有2中形式
R.layout.xx 是引用res/layout/xx.xml的佈局文件(inflate方法),R.id.xx是引用佈局文件裏面的組件,組件的id是xx...(findViewById方法)。看看R.java配置文件吧,R對文件分類管理,多寫幾個layout.xml後你會發現,所有的組件id都能用R.id.xx來查看,但是組件不在setContentView()裏面的layout中就無法使用,Activity.findViewById()會出現空指針異常

(1)Activity中的findViewById()

(2)View中的findViewById()
 
3. LayoutInflater.inflate()
將Layout文件轉換爲View,顧名思義,專門供Layout使用的Inflater。雖然Layout也是View的子類,但在android中如果想將xml中的Layout轉換爲View放入.java代碼中操作只能通過Inflater,而不能通過findViewById(),這一段描述有誤,看如下代碼看下面文檔寫的已經很清楚
---------------------------------------------------------------------------------------------
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

<LinearLayout android:id="@+id/placeslist_linearlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

</LinearLayout>
</ScrollView>
---------------------------------------------------------------------------------------------
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.placeslist_linearlayout);
linearLayout.addView(place_type_text);
這是可運行的,這上面的xml中,LinearLayout不再是Layout的代表,而只是一個普通的View。
轉自http://happyin1111.blog.163.com/blog/static/1641848012011128111337769/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章