一,解析LayoutInflater运行原理
从创建一个LayoutInflater的方式我们可以知道,LayoutInflater是系统提供的单例对象
LayoutInflater layoutInflater = getLayoutInflater();
↓
LayoutInflater layoutInflater = LayoutInflater.from(context);
↓
LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
boolean equals = getLayoutInflater().equals(LayoutInflater.from(this));
Log.e("equals", "value="+equals);
#输出value=true
#说明LayoutInflater具有全局属性
关于Inflate方法,主要分为2组,但前2组最终也是通过调用后2组中的某一个方法来实现的
inflate(int resource, ViewGroup root)
inflate(int resource, ViewGroup root, boolean attachToRoot)
-------------------------------------------------------------------------
inflate(XmlPullParser parser, ViewGroup root)
inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)
inflate方法最终会调用如下方法,当然这是必然的,因为我们需要解析这个布局文件
inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)
关于XmlPullParser parser解析器的获取,Android内部采用了XmlpullParser解析xml,这种解析类似与SAX Parser技术,效率高,因为它以IO流的方式进行解析和读取
我们来看一下XmlPullParser获取的这个实现方式
public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
if (DEBUG) System.out.println("INFLATING from resource: " + resource);
XmlResourceParser parser = getContext().getResources().getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
在Android内部XmlResourceParser继承自XmlPullParser
public interface XmlResourceParser extends XmlPullParser, AttributeSet {
/**
* Close this interface to the resource. Calls on the interface are no
* longer value after this call.
*/
public void close();
}
实际我们通过Resource获取到的是XmlResourceParser
XmlResourceParser xml = getResources().getXml(R.xml.gateway);
XmlResourceParser layout = getResources().getLayout(R.layout.fragment_main);
这里注意,其实获取资源的时候,都会通过XmlResourceParser,只是内部进行了必要的封装而已,有兴趣的 猿猿同学 可以查看Resource的实现代码
再来看看inflate的实现
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context)mConstructorArgs[0];
mConstructorArgs[0] = mContext;
View result = roo