一个android初学者对LayoutInflater的初理解

官方的解释:

Instantiates a layout XML file into its corresponding View objects. It is never used directly. Instead, usegetLayoutInflater() or 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对象。

一、LayoutInflater提供了3个接口  

1. LayoutInflater.Factory

2. LayoutInflater.Factory2

3.LayoutInflater.Filter

二、LayoutInflater提供了2个受保护的构造器

1.LayoutInflater(Context context)

2.LayoutInflater(LayoutInflater original, Context new Context)

三、14方法(包括方法名一样但参数不一样)

14个就不依依列出来,就我目前使用过的只有1.from(Context context)  2.getContext()  3.inflate(int resource, ViewGroup root)

这三个方法from(Context context) 在RecyclerVeiw列表设置适配器的时候,新建适配器时重写onCreateViewHolder用到了

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.company_items, parent, false);
    ViewHolder holder = new ViewHolder(view);
    return holder;
}
可以看到通过上面View的实例化就用到了三个方法:首先实例化View找到LayoutInflater再使用from(), from方法就是找到context上下文再调用inflate实例化xml布局文件。 


猜你喜欢

转载自blog.csdn.net/zingFeng_sky/article/details/80373755
今日推荐