View的如何被添加到屏幕窗口上的
通常我们的Activity中都会有这样设置布局的代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
而你有没有思考过代码中的activity_main布局是如何被添加到屏幕窗口上的呢?
让我们先来查看setContentView
的源码
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory2,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks2,
Window.OnWindowDismissedCallback, WindowControllerCallback,
AutofillManager.AutofillClient {
private Window mWindow;
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
public Window getWindow() {
return mWindow;
}
...
}
Window
是一个抽象类,setContentView
是类中的一个抽象方法,那我们再来看看,在这个抽象类的唯一实现类PhoneWindow.java
中,setContentView
方法是如何实现的。
注:PhoneWindow
在AS中查看不了,需要下载源码或者在源码查看网站查看,位置在 /frameworks/base/core/java/com/android/internal/policy/PhoneWindow.java
入口:PhoneWindow.class中的 setContentView方法
@Override
public void setContentView(int layoutResID) {
if (mContentParent == null) {
installDecor(); //@1
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);
} else {
mLayoutInflater.inflate(layoutResID, mContentParent); //@2
}
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
mContentParentExplicitlySet = true;
}
在这个方法中有两个重点
-
mContentParent
为空时,调用installDecor()
初始化父容器 -
mLayoutInflater.inflate(layoutResID, mContentParent);
解析传入的layoutResID
1. 先来看PhoneWindow.class中的 installDecor()方法
private void installDecor() {
mForceDecorInstall = false;
if (mDecor == null) {
mDecor = generateDecor(-1); //@1.1
mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
}
} else {
mDecor.setWindow(this);
}
if (mContentParent == null) {
mContentParent = generateLayout(mDecor); //@1.2
// Set up decor part of UI to ignore fitsSystemWindows if appropriate.
mDecor.makeOptionalFitsSystemWindows();
final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById(
R.id.decor_content_parent);
...
}
}
这个方法中的mDecor
变量就是最上层的View容器了,判断是否为空,如果为空,通过generateDecor(-1)
新建一个
1.1 来看PhoneWindow.java中的generateDecor(-1)方法
protected DecorView generateDecor(int featureId) {
Context context;
if (mUseDecorContext) {
Context applicationContext = getContext().getApplicationContext();
if (applicationContext == null) {
context = getContext();
} else {
context = new DecorContext(applicationContext, getContext());
if (mTheme != -1) {
context.setTheme(mTheme);
}
}
} else {
context = getContext();
}
return new DecorView(context, featureId, this, getAttributes());
}
通过该方法最后一行可见,返回的是一个DecorView
对象,而DecorView
是一个继承自FrameLayout
的容器对象。
注:AS同样查看不到DecorView.java,源码位置 /frameworks/base/core/java/com/android/internal/policy/DecorView.java
1.2 再来看PhoneWindow.java中的generateLayout(DecorView decor)方法
protected ViewGroup generateLayout(DecorView decor) {
...
// Inflate the window decor.
int layoutResource;
int features = getLocalFeatures();
// System.out.println("Features: 0x" + Integer.toHexString(features));
if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
layoutResource = R.layout.screen_swipe_dismiss;
setCloseOnSwipeEnabled(true);
} else if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
if (mIsFloating) {
TypedValue res = new TypedValue();
getContext().getTheme().resolveAttribute(
R.attr.dialogTitleIconsDecorLayout, res, true);
layoutResource = res.resourceId;
} else {
layoutResource = R.layout.screen_title_icons;
}
// XXX Remove this once action bar supports these features.
removeFeature(FEATURE_ACTION_BAR);
// System.out.println("Title Icons!");
} else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
&& (features & (1 << FEATURE_ACTION_BAR)) == 0) {
// Special case for a window with only a progress bar (and title).
// XXX Need to have a no-title version of embedded windows.
layoutResource = R.layout.screen_progress;
// System.out.println("Progress!");
} else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
// Special case for a window with a custom title.
// If the window is floating, we need a dialog layout
if (mIsFloating) {
TypedValue res = new TypedValue();
getContext().getTheme().resolveAttribute(
R.attr.dialogCustomTitleDecorLayout, res, true);
layoutResource = res.resourceId;
} else {
layoutResource = R.layout.screen_custom_title;
}
// XXX Remove this once action bar supports these features.
removeFeature(FEATURE_ACTION_BAR);
} else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
// If no other features and not embedded, only need a title.
// If the window is floating, we need a dialog layout
if (mIsFloating) {
TypedValue res = new TypedValue();
getContext().getTheme().resolveAttribute(
R.attr.dialogTitleDecorLayout, res, true);
layoutResource = res.resourceId;
} else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
layoutResource = a.getResourceId(
R.styleable.Window_windowActionBarFullscreenDecorLayout,
R.layout.screen_action_bar);
} else {
layoutResource = R.layout.screen_title;
}
// System.out.println("Title!");
} else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
layoutResource = R.layout.screen_simple_overlay_action_mode;
} else {
// Embedded, so no decoration is needed.
layoutResource = R.layout.screen_simple;
// System.out.println("Simple!");
}
mDecor.startChanging();
/**
* 方法重点!!!
**/
mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
if (contentParent == null) {
throw new RuntimeException("Window couldn't find content container view");
}
if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
ProgressBar progress = getCircularProgressBar(false);
if (progress != null) {
progress.setIndeterminate(true);
}
}
...
return contentParent;
}
这个方法实际上很长,其中很多内容是获取到主题后,根据主题来设置Window
特性,例如
if (a.getBoolean(R.styleable.Window_windowActionBarOverlay, false)) {
requestFeature(FEATURE_ACTION_BAR_OVERLAY);
}
我们主要关注layoutResource
的初始化操作,根据features等条件的不同,layoutResource
会被赋上不同的值。例如:R.layout.screen_simple,R.layout.screen_swipe_dismiss,R.layout.screen_title_icons 等等。
然后调用mDecor
对象的方法:
mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
追踪到DecorView
的onResourcesLoaded
方法中
void onResourcesLoaded(LayoutInflater inflater, int layoutResource) {
if (mBackdropFrameRenderer != null) {
loadBackgroundDrawablesIfNeeded();
mBackdropFrameRenderer.onResourcesLoaded(
this, mResizingBackgroundDrawable, mCaptionBackgroundDrawable,
mUserCaptionBackgroundDrawable, getCurrentColor(mStatusColorViewState),
getCurrentColor(mNavigationColorViewState));
}
mDecorCaptionView = createDecorCaptionView(inflater);
final View root = inflater.inflate(layoutResource, null);
if (mDecorCaptionView != null) {
if (mDecorCaptionView.getParent() == null) {
addView(mDecorCaptionView,
new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
mDecorCaptionView.addView(root,
new ViewGroup.MarginLayoutParams(MATCH_PARENT, MATCH_PARENT));
} else {
// Put it below the color views.
addView(root, 0, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
mContentRoot = (ViewGroup) root;
initializeElevation();
}
可以看到,就是将传入的layoutResource
通过addView
加到DecorView
对象上。
再然后回到PhoneWindow
的generateLayout
方法,看到onResourcesLoaded
之后执行了
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
查到mDecor
上的容器【系统ID为 com.android.internal.R.id.content】,并返回contentParent。
2. 再来看PhoneWindow.class中的 mLayoutInflater.inflate(layoutResID, mContentParent);
实际上,mContentParent
就是在installDecor()
方法中由generateLayout(mDecor)
赋值的提供给用户填充的容器,无论系统做出什么判断,将layoutResource赋值成什么布局,它总要包含一个固定的容器ID
,而这个id为@android:id/content的容器就会暴露给用户,用户setContentView(View view)
的布局也就有了父容器。
追踪到LayoutInflater.java
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser);
// Context对象
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
// 父视图
View result = root;
try {
// Look for the root node.
int type;
// 找到root元素
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
final String name = parser.getName();
// 解析merge标签
if (TAG_MERGE.equals(name)) {
// 如果是merge标签调用新方法,将merge标签内的元素全部加载到父视图中
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// 通过xml的tag来解析根视图
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
// 不是merge标签,直接解析布局中的视图
ViewGroup.LayoutParams params = null;
if (root != null) {
// 生成布局参数
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
temp.setLayoutParams(params);
}
}
// Inflate all children under temp against its context.
// 解析temp视图下的所有view
rInflateChildren(parser, temp, attrs, true);
// 如果root不为空并且attachToRoot为true,将temp加入到父视图中
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// 如果root为空 或者 attachToRoot为false,返回的结果就是temp
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
throw ie;
} catch (Exception e) {
throw ie;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}
return result;
}
}
最终调用public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
方法,其中第一个参数是xml解析器,第二个参数是要解析布局的父视图,第三个参数标识是否需要加入到父视图中。
上面的inflate方法所做的操作主要有以下几步:
- 解析xml的根标签
- 如果根标签是
merge
,那么调用rInflate
解析,将merge
标签下的所有子View直接添加到根标签中 - 如果不是merge,调用
createViewFromTag
解析该元素 - 调用
rInflate
解析temp中的子View,并将这些子View添加到temp中 - 通过
attachToRoot
,返回对应解析的根视图
我们先看createViewFromTag
方法:
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
try {
View view;
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
// 通过.来判断是自定义View还是内置View
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
return view;
} catch (InflateException e) {
throw e;
} catch (ClassNotFoundException e) {
throw ie;
}
}
我们可以发现,解析View的时候是通过.
来判断是内置的View还是自定义的View的,那么我们就能知道为什么在写布局文件中自定义的View需要完整路径了。
在解析内置View的时候就是通过类似于PhoneLayoutInflater
的onCreateView
的解析方式,通过在name
前加上android.view.
最终也是调用createView
来解析。
而自定义view则是在调用createView(name, null, attrs)
时,第二个参数的前缀传递null。
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
// 从缓存中获取view的构造函数
Constructor<? extends View> constructor = sConstructorMap.get(name);
if (constructor != null && !verifyClassLoader(constructor)) {
constructor = null;
sConstructorMap.remove(name);
}
Class<? extends View> clazz = null;
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
// 如果没有缓存
if (constructor == null) {
// 如果前缀不为空构造完整的View路径并加载该类
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
// 获取该类的构造函数
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
// 将构造函数加入缓存中
sConstructorMap.put(name, constructor);
} else {
}
Object[] args = mConstructorArgs;
args[1] = attrs;
// 通过反射构建View
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
// Use the same context when inflating ViewStub later.
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
return view;
}
}
createView
相对简单,通过判断前缀,来构建View的完整路径,并将该类加载到虚拟机中,获取构造函数并缓存,再通过构造函数创建该View对象,并返回。这个时候我们就获得了根视图。接着调用rInflateChildren
方法解析子View,并最终调用rInflate
方法:
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
// 获取树的深度,通过深度优先遍历
final int depth = parser.getDepth();
int type;
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
if (TAG_REQUEST_FOCUS.equals(name)) {
parseRequestFocus(parser, parent);
} else if (TAG_TAG.equals(name)) {// 解析tag标签
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {// 解析include标签
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {// 解析到merge标签,并报错
throw new InflateException("<merge /> must be the root element");
} else {
// 解析到普通的子View,并调用createViewFromTag获得View对象
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
// 递归解析
rInflateChildren(parser, view, attrs, true);
// 将View加入到父视图中
viewGroup.addView(view, params);
}
}
if (finishInflate) {
parent.onFinishInflate();
}
}
rInflate
方法通过深度优先遍历的方式来构造视图树,当解析到一个View的时候就再次调用rInflate
方法,直到将路径下的最后一个元素,并最终将View加入到父视图中。
总结
- 创建顶层布局
DecorView
,继承自FrameLayout
的ViewGroup容器,是PhoneWindow
对象持有的一个实例,是所有应用程序的顶层View,在系统内部进行初始化。 - 在
DecorView
初始化完成后,系统会根据应用程序的主题特性,在顶层布局中加载基础布局ViewGroup
,例如R.layout.screen_simple.xml等等,无论如何这个基础容器中一定会有一个id为android.internal.R.id.content的容器,这个容器是一个FrameLayout
。 - 开发者通过
contentView
,将自己的布局添加到基础布局中的FrameLayout
中
网友评论