转载请注明链接:https://blog.csdn.net/feather_wch/article/details/79900081
本文详细分析从XML创建View的原理
通过XML创建View的原理
版本:2018/8/27-1
原理
本质原理:
1. Activity是通过Factory
进行View的创建
2. 自定义Factory
就能拦截创建过程,创建自己的View
OnCreate流程
1、AppCompatActivity的OnCreate流程
//AppCompatActivity.java
protected void onCreate(@Nullable Bundle savedInstanceState) {
final AppCompatDelegate delegate = getDelegate();
//1. 初始化LayoutInflater,并且设置过Factory(没有设置过就新建)
delegate.installViewFactory();
//2. 执行正常的onCreate流程
delegate.onCreate(savedInstanceState);
//xxx
super.onCreate(savedInstanceState);
}
//AppCompatDelegateImpV9.java
public void installViewFactory() {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
//1. 没有Factory,系统会创建一个Factory去进行XML到View的转换
if (layoutInflater.getFactory() == null) {
LayoutInflaterCompat.setFactory2(layoutInflater, this);
} else {
if (!(layoutInflater.getFactory2() instanceof AppCompatDelegateImplV9)) {
Log.i(TAG, "The Activity's LayoutInflater already has a Factory installed" + " so we can not install AppCompat's");
}
}
}
//LayoutInflaterCompat.java
public static void setFactory2(@NonNull LayoutInflater inflater, @NonNull LayoutInflater.Factory2 factory) {
//1. 能将Factory接口绑定到创建View的LayoutInflater(IMPL类型为LayoutInflaterCompatBaseImpl)
IMPL.setFactory2(inflater, factory);
}
//LayoutInflaterCompat.java内部类LayoutInflaterCompatBaseImpl:
static class LayoutInflaterCompatBaseImpl {
//xxx
public void setFactory2(LayoutInflater inflater, LayoutInflater.Factory2 factory) {
inflater.setFactory2(factory);
//xxx
}
}
//LayoutInflater.java-完成Factory的创建
public void setFactory2(Factory2 factory) {
//xxx