LayoutInflater
在安卓开发中,涉及View的操作我们经常需要使用到LayoutInflater
这个类。这个类的作用,我们看官方问档,
Instantiates a layout XML file into its corresponding View objects. It is never used directly. Instead, use Activity.getLayoutInflater() or Context.getSystemService(Class) to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on
To create a new LayoutInflater with an additional LayoutInflater.Factory for your own views, you can use cloneInContext(Context) to clone an existing ViewFactory, and then call setFactory(LayoutInflater.Factory) on it to include your Factory.
For performance reasons, view inflation relies heavily on pre-processing of XML files that is done at build time. Therefore, it is not currently possible to use LayoutInflater with an XmlPullParser over a plain XML file at runtime; it only works with an XmlPullParser returned from a compiled resource (R.something file.)
Instances of this class must be obtained using Context.getSystemService(Class) with the argument LayoutInflater.class or Context.getSystemService(String) with the argument Context.LAYOUT_INFLATER_SERVICE.
LayoutInflater类的作用是,将xml布局文件实例化为它对应的View对象。这个类不能直接使用,因为他是一个抽象类,只能使用他子类的实现。一般,我们通过getLayoutInflater()
方法或者 getSystemService(String)
方法来获得该类的实例,通过以上两个方法获得的LayoutInflater类实例,已经和当前的上下文关联起来,并且已经正确配置在当前程序运行的设备上。
- getLayoutInflater()
Activity类有这个方法,不需要传入参数,在Activity中直接调用即可。Fragment类也有这个方法,但是需要传入一个Bundle对象作为参数。可以看到,通过该方法获得的LayoutInflater类对象和上下文环境相配合。
- getSystemService(String)
这个方法,需要传入Context的成员变量作为参数,获得相应的对象,要获得LayoutInflater对象,需要传入Context.LAYOUT_INFLATER_SERVICE
以上介绍的LayoutInflater类是Android系统为我们提供的通用类,如果我们想要为我们的View对象创建专用的LayoutInflater类,则可以用到LayoutInflater.Factory ,这是一个LayoutInflater类内部的接口,通过工厂设计模式可以使我们获得定制的专用LayoutInflater类。我们可以使用cloneInContext(Context)来克隆一个已经存在的ViewFactory,然后调用setFactory(LayoutInflater.Factory)方法,将我们创建好的工厂包括进来。这里意思是:当我在一个上下文环境中创建好了一个LayoutInflater工厂之后,我们又想在另一个上下文环境中使用这个LayoutInflater工厂,那该怎么办?这里说的一种方法
是,我们在当前上下文环境中,使用LayoutInflater类对象调用cloneInContext(Context)方法,其中的参数填写新上下文对象,因为我们要在新的上下文环境中使用。然后接着调用setFactory(LayoutInflater.Factory)方法,
其中的参数就是我们目前创建的LayoutInflater工厂。这样创建完成后,我们在新上下文环境中,就可以调用目前上下文环境中绑定了LayoutInflater工厂的LayoutInflater类对象了。
xml文件在创建阶段的前处理过程严重影响View对象填充阶段的性能(进而影响整体软件的性能),这是因为inflate方法内部使用的pull解析,若是xml文件在进行填充之前已经被xml解析了,那么inflate方法在使用时就非常轻松,否则会非常困难。因此,我们不会使用LayoutInflater类处理普通的xml文件,而是用来处理已经编译的xml文件,例如R.··········,这样的xml文件会返回一个已经解析了xml文件的pull解析器,而普通的xml文件返回的解析器则不然。