实例化Layout中的布局文件(xml)

  • 什么是LayoutInflater

  This class is used to instantiate layout XML file into its corresponding View objects.源码分析

这个类做用是把把xml类型的布局转化成相应的View对象布局

  • 在实际开发中LayoutInflater这个类仍是很是有用的,它的做用相似于findViewById()。

  不一样点是LayoutInflater是用来找res/layout/下的xml布局文件,而且实例化;而findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等)。spa

具体做用: 一、对于一个没有被载入或者想要动态载入的界面,都须要使用LayoutInflater.inflate()来载入;code

      二、对于一个已经载入的界面,就可使用Activity.findViewById()方法来得到其中的界面元素。xml

 

  • LayoutInflater 实例化的三种方式
  1. LayoutInflater inflater = getLayoutInflater(); //调用Activity的getLayoutInflater()
  2. LayoutInflater localinflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //context需定义
  3. LayoutInflater inflater = LayoutInflater.from(context); //context需定义

经过源码分析,这三种方式最终的本质都是调用了Context.getSystemService()。htm

  实例化后经过inflate方法加载具体的布局资源。有如下几种方式:对象

  1. public View inflate (int resource, ViewGroup root) 
  2. public View inflate (XmlPullParser parser, ViewGroup root) 
  3. public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot) 
  4. public View inflate (int resource, ViewGroup root, boolean attachToRoot)

解析:若是将root参数设置为null,则忽略xml布局文件中的layout_x参数,(通常状况下选择Null便可)blog

   若是root不为null,而且把attachToRoot=true,那么就会根据root生成一个布局文件View的LayoutParam对象,而且将这个View添加到root中去,而且返回这个root的View。资源

  具体例子:开发

LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View view = inflater.inflate(R.layout.custom, null); 
EditText editText = (EditText)view.findViewById(R.id.content);
  • inflate方法与 findViewById 方法的区别
  1. inflater 是用来找 res/layout下的 xml 布局文件,而且实例化;
  2. findViewById() 是找具体 xml 布局文件中的具体 widget 控件(如:Button、TextView 等)。
  •  inflate方法与 SetContentView方法的区别
  1. SetContentView一旦调用, layout就会马上显示UI
  2. inflate只会把Layout造成一个以view类实现成的对象。有须要时再用setContentView(view)显示出来

 程序猿必读

相关文章
相关标签/搜索