LayoutInflater的inflate函数用法详解
LayoutInflater作用是将layout的xml布局文件实例化为View类对象。获取LayoutInflater的方法有如下三种
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.main, null);
LayoutInflater inflater = LayoutInflater.from(context); (该方法实质就是第一种方法,可参考源代码)
View layout = inflater.inflate(R.layout.main, null);
LayoutInflater inflater = getLayoutInflater();(在Activity中可以使用,实际上是View子类下window的一个函数)
View layout = inflater.inflate(R.layout.main, null);
setContentView 和 inflate 的区别
setContentView()一旦调用, layout就会立刻显示UI;而inflate只会把Layout形成一个以view类实现成的对象,有需要时再用setContentView(view)显示出来。一般在activity中通过setContentView()将界面显示出来,但是如果在非activity中如何对控件布局设置操作了,这就需要LayoutInflater动态加载。
public View inflate(int Resourece,ViewGroup root)
作用:填充一个新的视图层次结构从指定的XML资源文件中
reSource:View的layout的ID
root: 生成的层次结构的根视图
return 填充的层次结构的根视图。如果参数root提供了,那么root就是根视图;否则填充的XML文件的根就是根视图。
其余几个重载的inflate函数类似。
例子:
1.普通Activity中使用inflate函数1
View view = View.inflate(this, R.layout.splash_animation, null);
//splash_animation.xml file
setContentView(view);
2.普通Activity中使用inflate函数2
View selectView = getLayoutInflater().inflate(R.layout.list, null);
final ListView listview = (ListView)(selectView.findViewById(R.id.list));
new AlertDialog.Builder(BlockList.this).setView(selectView).setPositiveButton("OK", new DialogInterface.OnClickListener(){
});
3.在Fragment类的onCreateView中利用形参中的LayoutInflator inflater
public class AuctionListFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater
, ViewGroup container, Bundle savedInstanceState)
{
// 加载/res/layout/目录下的function_list.xml布局文件
View rootView = inflater.inflate(R.layout.auction_list,
container, false);
auctionList = (ListView) rootView.findViewById(
R.id.auction_list);
return rootView;
}
}
4.在Fragment类的自定义函数中使用 getActivity().getLayoutInflater() .inflate()....
public class ViewItemFragment extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater
, ViewGroup container, Bundle savedInstanceState)
{
}
private void viewItemDetail(int position)
{
// 加载detail.xml界面布局代表的视图
View detailView = getActivity().getLayoutInflater()
.inflate(R.layout.detail, null);
}