【Android】LayoutInflater

LayoutInflater的作用

  LayoutInflater的作用类似于findViewById()。

  不同点是:

  LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化为View类对象。

  对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素,因为在一个Activity里对应的是setConentView()的那个layout里的组件。

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

  因此如果你的Activity里如果用到别的layout,比如对话框上的layout,你还要设置对话框上的layout里的组件(像图片ImageView,文字TextView)上的内容,你就必须用inflate()先将对话框上的layout找出来,然后再用这个layout对象去找到它上面的组件,所以对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入。 

  它可以有很多地方可以使用,如BaseAdapter的getView中,自定义Dialog中取得view中的组件widget等等。

获得 LayoutInflater 实例的三种方式

LayoutInflater inflater = getLayoutInflater();//调用Activity的getLayoutInflater()
LayoutInflater inflater = LayoutInflater.from(context);  
LayoutInflater inflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);

   第一种方式

LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.ID, null);

   第二种方式

LayoutInflater inflater = LayoutInflater.from(this); 
View view=inflater.inflate(R.layout.ID, null);
//或者干脆并成一句:
View view=LayoutInflater.from(this).inflate(R.layout.ID, null);

示例工程

  参见:http://www.cnblogs.com/tt_mc/archive/2010/05/28/1746307.html

原文地址:https://www.cnblogs.com/lcw/p/3348131.html