LayoutInflater的作用

 

 Inflater英文意思是膨胀,在安卓中是“扩展”的意思。 
LayoutInflater的作用类似于 findViewById(),不同点是LayoutInflater是用来找layout文件夹下的xml布局文件,并且实例化!而 findViewById()是找具体某一个xml下的具体 widget控件(如:Button,TextView等)。

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

Java代码
  1. view plaincopy to clipboardprint?  
  2. LayoutInflater inflater = LayoutInflater.from(this);     
  3. View view=inflater.inflate(R.layout.ID, null);    
  4. 或者干脆并成一句:    
  5. View view=LayoutInflater.from(this).inflate(R.layout.ID, null);    



另一种方法: 

Java代码
  1. view plaincopy to clipboardprint?  
  2. LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);    
  3. View view=inflater.inflate(R.layout.ID, null);    


上面2种方法本质上是一样的,看下面的源码,form()调用的就是getSystemService(): 
Java代码
  1. Java代码  
  2. public static LayoutInflater from(Context context) {       
  3.     LayoutInflater LayoutInflater =       
  4.             (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);       
  5.     if (LayoutInflater == null) {       
  6.         throw new AssertionError("LayoutInflater not found.");       
  7.     }       
  8.     return LayoutInflater;       
  9. }     



原文地址:https://www.cnblogs.com/xilin/p/2603890.html