Android LayoutInflater的使用

Inflater英文意思是膨胀,在Android中应该是扩展的意思吧。 
LayoutInflater的做用相似于 findViewById(),不一样点是LayoutInflater是用来找layout文件夹下的xml布局文件,而且实例化!而 findViewById()是找具体某一个xml下的具体 widget控件(如:Button,TextView等)。 php

获取它的用法有3种: html

方法1: java

由LayoutInflater的静态函数:from(Context context) 获取: android

static LayoutInflater from(Context context); app

如: 函数

LayoutInflater inflater = LayoutInflater.from(this);
View view=inflater.inflate(R.layout.ID, null);
//或写成:
View view=LayoutInflater.from(this).inflate(R.layout.ID, null);

方法2: 布局

由服务获取: this

LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);

方法3: spa

调用Activity的getLayoutInflater() 函数获取LayoutInflater 对象。 指针


setContentView和inflate区别

通常用LayoutInflater作一件事:inflate

inflate这个方法总共有四种形式(见下面),目的都是把xml表述的layout转化为View对象
其中有一个比较经常使用,View inflate(int resource, ViewGroup root),另三个,其实目的和这个差很少。
int resource,也就是resource/layout文件在R文件中对应的ID,这个必须指定。
而ViewGroup root则能够是null,null时就只建立一个resource对应的View,不是null时,会将建立的view自动加为root的child。

setContentView()一旦调用, layout就会马上显示UI;而inflate只会把Layout造成一个以view类实现成的对象,有须要时再用setContentView(view)显示出来
通常在activity中经过setContentView()将界面显示出来,可是若是在非activity中如何对控件布局设置操做了,这需LayoutInflater动态加载
< TextView
android:id="@+id/tview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="ATAAW.COM"
/>
< Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/button"
android:text="按钮"
/>
在程序中动态加载以上布局。
LayoutInflater flater = LayoutInflater.from(this);
View view = flater.inflate(R.layout.example, null);
获取布局中的控件。
button = (Button) view.findViewById(R.id.button);//这里的view为上面获取的view对象
textView = (TextView)view.findViewById(R.id.tview);

LayoutInflater.inflate()将Layout文件转换为View,专门供Layout使用的Inflater。虽然Layout也是View的子类,但在android中若是想将xml中的Layout转换为View放入.java代码中操做,只能经过Inflater,而不能经过findViewById()。 

findViewById有两种形式 
R.layout.xx是引用res/layout/xx.xml的布局文件(inflate 方法),R.id.xx是引用布局文件里面的组件,组件的id是xx(findViewById方法)。全部的组件id都能用R.id.xx来查看,可是组件不在setContentView()里面的layout中就没法使用,Activity.findViewById()会出现空指针异常 
a. activity中的findViewById(int id) 
b. View 中的findViewById(int id) 
不一样点是LayoutInflater是用来找layout下xml布局文件,而且实例化!而findViewById()是找具体xml下的具体 widget控件(如:Button,TextView等)。

话外:

通俗的说,inflate就至关于将一个xml中定义的布局找出来.

由于在一个Activity里若是直接用findViewById()的话,对应的是setConentView()的那个layout里的组件.

所以若是你的Activity里若是用到别的layout,好比对话框上的layout,你还要设置对话框上的layout里的组件(像图片ImageView,文字TextView)上的内容,你就必须用inflate()先将对话框上的layout找出来,而后再用这个layout对象去找到它上面的组件,如:
View view = View.inflate(this, R.layout.dialog_layout, null);
TextView dialogTV = (TextView) view.findViewById(R.id.dialog_tv);
dialogTV.setText("abcd");

若是组件R.id.dialog_tv是对话框上的组件,而你直接用this.findViewById(R.id.dialog_tv)确定会报错.
相关文章
相关标签/搜索