当前位置:   article > 正文

Android UI深度理解:Activity UI视图结构_android activity层级

android activity层级

Activity UI视图结构

Android UI层级结构图
每个Activity都会获得一个窗口,那就是Window,它用于绘制用户的UI界面
Window是一个抽象类,提供了绘制窗口的一组通用API,PhoneWindow是它的唯一实现类
DecorView是所有应用窗口的根节点。是FrameLayout的子类
PhoneWindow内部实现xml布局文件的加载,容器为根据feature进行加载的对应的layout布局中android:id="@android:id/content"的ViewGroup类型的容器

在这里插入图片描述

 源码分析

xml布局文件的使用

  1. public class MainActivity extends Activity {
  2. @Override
  3. protected void onCreate(@Nullable Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. //R.layout.xxx为引入自定义xml布局文件xxx.xml
  6. setContentView(R.layout.xxx);
  7. }
  8. ......
  9. }

针对上面setContentView(R.layout.xxx);的使用,作为Android APP开发者来说,深入骨髓的说法已经不为过了,但是就这么一个方法,是怎么生成上图描述的UI层级结构的?
这就是我们今天的核心目标,我们将以源码分析的方式进行深度学习。

setContentView(R.layout.xxx)
 

  1. /**
  2. * Set the activity content from a layout resource. The resource will be
  3. * inflated, adding all top-level views to the activity.
  4. * 译文:从布局资源中设置Activity的视图内容,该资源将会被inflated并且把所有的顶层视图添加到Activity中
  5. * @param layoutResID Resource ID to be inflated.
  6. *
  7. * @see #setContentView(android.view.View)
  8. * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
  9. */
  10. public void setContentView(@LayoutRes int layoutResID) {
  11. getWindow().setContentView(layoutResID);
  12. initWindowDecorActionBar();//这是一个ActionBar的创建过程,暂不参与本次流程学习
  13. }

getWindow().setContentView(layoutResID);引出了一个Window

android.view.PhoneWindow

android.view.PhoneWindow:Window(抽象类)的唯一实现类

  1. /**
  2. * Abstract base class for a top-level window look and behavior policy. An
  3. * instance of this class should be used as the top-level view added to the
  4. * window manager. It provides standard UI policies such as a background, title
  5. * area, default key processing, etc.
  6. * 译文:顶层窗口外观和行为策略的抽象基类。这个类的一个实例应该用作添加到窗口管理器的顶级视图。
  7. *
  8. * 它提供了标准的UI策略,如背景、标题区域、默认键处理等
  9. * <p>The only existing implementation of this abstract class is
  10. * android.view.PhoneWindow, which you should instantiate when needing a
  11. * Window.
  12. * 译文:android.view.PhoneWindow是该抽象类的唯一实现类,你在需要一个Window时应该实例
  13. */
  14. public abstract class Window {
  15. ......
  16. }

根据Window类注释,针对getWindow().setContentView(layoutResID)的调用,我们应该到PhoneWindow中阅读setContentView方法的实现内容

  1. @Override
  2. public void setContentView(int layoutResID) {
  3. // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
  4. // decor, when theme attributes and the like are crystalized. Do not check the feature
  5. // before this happens.
  6. if (mContentParent == null) {
  7. installDecor();
  8. } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
  9. mContentParent.removeAllViews();
  10. }
  11. if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {//执行动画相关操作
  12. final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
  13. getContext());
  14. transitionTo(newScene);
  15. } else {
  16. //layoutResID是一个xml布局,它将在这里被添加到mContentParent这个容器中,最后进行View视图的显示
  17. mLayoutInflater.inflate(layoutResID, mContentParent);
  18. }
  19. mContentParent.requestApplyInsets();
  20. final Callback cb = getCallback();
  21. if (cb != null && !isDestroyed()) {
  22. cb.onContentChanged();
  23. }
  24. mContentParentExplicitlySet = true;
  25. }

PhoneWindow的实例化过程

在Activity中attach方法内的第 12 行,PhoneWindowNew的方式被实例化成mWindow对象

  1. final void attach(Context context, ActivityThread aThread,
  2. Instrumentation instr, IBinder token, int ident,
  3. Application application, Intent intent, ActivityInfo info,
  4. CharSequence title, Activity parent, String id,
  5. NonConfigurationInstances lastNonConfigurationInstances,
  6. Configuration config, String referrer, IVoiceInteractor voiceInteractor,
  7. Window window, ActivityConfigCallback activityConfigCallback) {
  8. attachBaseContext(context);
  9. mFragments.attachHost(null /*parent*/);
  10. //PhoneWindow 在这里被实例化出来了
  11. mWindow = new PhoneWindow(this, window, activityConfigCallback);
  12. mWindow.setWindowControllerCallback(this);
  13. mWindow.setCallback(this);
  14. mWindow.setOnWindowDismissedCallback(this);
  15. mWindow.getLayoutInflater().setPrivateFactory(this);
  16. ......
  17. /*并且在以下代码中,我们可以发现到Activity的相关生命周期的调用*/
  18. activity.mCalled = false;
  19. if (r.isPersistable()) {
  20. mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
  21. } else {
  22. mInstrumentation.callActivityOnCreate(activity, r.state);
  23. }
  24. if (!activity.mCalled) {
  25. throw new SuperNotCalledException(
  26. "Activity " + r.intent.getComponent().toShortString() +
  27. " did not call through to super.onCreate()");
  28. }
  29. r.activity = activity;
  30. r.stopped = true;
  31. if (!r.activity.mFinished) {
  32. activity.performStart();
  33. r.stopped = false;
  34. }
  35. if (!r.activity.mFinished) {
  36. if (r.isPersistable()) {
  37. if (r.state != null || r.persistentState != null) {
  38. mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
  39. r.persistentState);
  40. }
  41. } else if (r.state != null) {
  42. mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
  43. }
  44. }
  45. if (!r.activity.mFinished) {
  46. activity.mCalled = false;
  47. if (r.isPersistable()) {
  48. mInstrumentation.callActivityOnPostCreate(activity, r.state,
  49. r.persistentState);
  50. } else {
  51. mInstrumentation.callActivityOnPostCreate(activity, r.state);
  52. }
  53. if (!activity.mCalled) {
  54. throw new SuperNotCalledException(
  55. "Activity " + r.intent.getComponent().toShortString() +
  56. " did not call through to super.onPostCreate()");
  57. }
  58. }
  59. }

attach则是在ActivityThread类中的performLaunchActivity被调用

  1. private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
  2. // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
  3. ......
  4. Activity activity = null;
  5. ......
  6. try {
  7. Application app = r.packageInfo.makeApplication(false, mInstrumentation);
  8. ......
  9. if (activity != null) {
  10. ......
  11. appContext.setOuterContext(activity);
  12. //这里调用了Activity的attach方法,实现了PhoneWindow的初始化
  13. activity.attach(appContext, this, getInstrumentation(), r.token,
  14. r.ident, app, r.intent, r.activityInfo, title, r.parent,
  15. r.embeddedID, r.lastNonConfigurationInstances, config,
  16. r.referrer, r.voiceInteractor, window, r.configCallback);
  17. ......
  18. }
  19. r.paused = true;
  20. mActivities.put(r.token, r);
  21. } catch (SuperNotCalledException e) {
  22. throw e;
  23. } catch (Exception e) {
  24. if (!mInstrumentation.onException(activity, e)) {
  25. throw new RuntimeException(
  26. "Unable to start activity " + component
  27. + ": " + e.toString(), e);
  28. }
  29. }
  30. return activity;
  31. }

DecorView如何添加到Window窗口

在这里插入图片描述

关注点1:requestFeature(int featureId)

  1. // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
  2. // decor, when theme attributes and the like are crystalized. Do not check the feature
  3. // before this happens.

 

该处是一处备注说明,大致意思为:
当主题属性和类似的东西被具体化时,Window在被加载的过程中可能被设置FEATURE_CONTENT_TRANSITIONS,在此之前不要检测该feature属性
该处也正是说明了为什么我们在使用Window的requestFeature(int featureId)函数必须在setContentView之前才有用,并且在下面还会进一步分析这个条件

关注点2:mContentParent
在第 6 行代码中,我们关注到了if (mContentParent == null)的判空条件,那么mContentParent就应该是一个值得关注的对象,那么它是个什么对象呢

  1. // This is the view in which the window contents are placed. It is either
  2. // mDecor itself, or a child of mDecor where the contents go.
  3. ViewGroup mContentParent;

它是一个ViewGroup容器,并且注释写的很清楚:
这是放置Window内容的视图。它要么是mDecor本身,要么是mDecor的子内容。
接地气一点的意思就是:mContentParent就是用来加载我们想要的xml布局内容的容器
其中注释提及到了mDecor,并且在第 7 行的installDecor();方法内也体现到了mDecor对象

关注点3:mDecor
 

  1. // This is the top-level view of the window, containing the window decor.
  2. private DecorView mDecor;
  1. /** @hide */
  2. public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks {
  3. ......
  4. }

对mDecor的分析结果就是:mDecor是Window窗口视图的根节点,它继承了FrameLayout容器

关注点4:FEATURE_CONTENT_TRANSITIONS
FEATURE_CONTENT_TRANSITIONS是Activity的转场动画,就是用来设置动画操作的标志

关注点5:mLayoutInflater.inflate(layoutResID, mContentParent);
layoutResID是一个xml布局,取决于feature值所对应的布局文件,它将在这里被添加到mContentParent这个容器中,最后进行View视图的显示

结合关注点1-5源码分析

installDecor()

  1. if (mContentParent == null) {
  2. installDecor();
  3. } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
  4. mContentParent.removeAllViews();
  5. }

如果mContentParent != nulll的时候,那么这里会清空容器中的所有View -> mContentParent.removeAllViews();
那么为null的时候,installDecor();初始化了什么内容

  1. private void installDecor() {
  2. mForceDecorInstall = false;
  3. if (mDecor == null) {
  4. mDecor = generateDecor(-1);//实例出一个DecorView对象
  5. mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
  6. mDecor.setIsRootNamespace(true);
  7. if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
  8. mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
  9. }
  10. } else {
  11. mDecor.setWindow(this);
  12. }
  13. if (mContentParent == null) {
  14. mContentParent = generateLayout(mDecor);
  15. // Set up decor part of UI to ignore fitsSystemWindows if appropriate.
  16. mDecor.makeOptionalFitsSystemWindows();
  17. final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById(
  18. R.id.decor_content_parent);
  19. if (decorContentParent != null) {
  20. mDecorContentParent = decorContentParent;
  21. mDecorContentParent.setWindowCallback(getCallback());
  22. if (mDecorContentParent.getTitle() == null) {
  23. mDecorContentParent.setWindowTitle(mTitle);
  24. }
  25. final int localFeatures = getLocalFeatures();
  26. for (int i = 0; i < FEATURE_MAX; i++) {
  27. if ((localFeatures & (1 << i)) != 0) {
  28. mDecorContentParent.initFeature(i);
  29. }
  30. }
  31. mDecorContentParent.setUiOptions(mUiOptions);
  32. if ((mResourcesSetFlags & FLAG_RESOURCE_SET_ICON) != 0 ||
  33. (mIconRes != 0 && !mDecorContentParent.hasIcon())) {
  34. mDecorContentParent.setIcon(mIconRes);
  35. } else if ((mResourcesSetFlags & FLAG_RESOURCE_SET_ICON) == 0 &&
  36. mIconRes == 0 && !mDecorContentParent.hasIcon()) {
  37. mDecorContentParent.setIcon(
  38. getContext().getPackageManager().getDefaultActivityIcon());
  39. mResourcesSetFlags |= FLAG_RESOURCE_SET_ICON_FALLBACK;
  40. }
  41. if ((mResourcesSetFlags & FLAG_RESOURCE_SET_LOGO) != 0 ||
  42. (mLogoRes != 0 && !mDecorContentParent.hasLogo())) {
  43. mDecorContentParent.setLogo(mLogoRes);
  44. }
  45. // Invalidate if the panel menu hasn't been created before this.
  46. // Panel menu invalidation is deferred avoiding application onCreateOptionsMenu
  47. // being called in the middle of onCreate or similar.
  48. // A pending invalidation will typically be resolved before the posted message
  49. // would run normally in order to satisfy instance state restoration.
  50. PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
  51. if (!isDestroyed() && (st == null || st.menu == null) && !mIsStartingWindow) {
  52. invalidatePanelMenu(FEATURE_ACTION_BAR);
  53. }
  54. } else {
  55. mTitleView = findViewById(R.id.title);
  56. if (mTitleView != null) {
  57. if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) {
  58. final View titleContainer = findViewById(R.id.title_container);
  59. if (titleContainer != null) {
  60. titleContainer.setVisibility(View.GONE);
  61. } else {
  62. mTitleView.setVisibility(View.GONE);
  63. }
  64. mContentParent.setForeground(null);
  65. } else {
  66. mTitleView.setText(mTitle);
  67. }
  68. }
  69. }
  70. if (mDecor.getBackground() == null && mBackgroundFallbackResource != 0) {
  71. mDecor.setBackgroundFallback(mBackgroundFallbackResource);
  72. }
  73. // Only inflate or create a new TransitionManager if the caller hasn't
  74. // already set a custom one.
  75. if (hasFeature(FEATURE_ACTIVITY_TRANSITIONS)) {
  76. if (mTransitionManager == null) {
  77. final int transitionRes = getWindowStyle().getResourceId(
  78. R.styleable.Window_windowContentTransitionManager,
  79. 0);
  80. if (transitionRes != 0) {
  81. final TransitionInflater inflater = TransitionInflater.from(getContext());
  82. mTransitionManager = inflater.inflateTransitionManager(transitionRes,
  83. mContentParent);
  84. } else {
  85. mTransitionManager = new TransitionManager();
  86. }
  87. }
  88. mEnterTransition = getTransition(mEnterTransition, null,
  89. R.styleable.Window_windowEnterTransition);
  90. mReturnTransition = getTransition(mReturnTransition, USE_DEFAULT_TRANSITION,
  91. R.styleable.Window_windowReturnTransition);
  92. mExitTransition = getTransition(mExitTransition, null,
  93. R.styleable.Window_windowExitTransition);
  94. mReenterTransition = getTransition(mReenterTransition, USE_DEFAULT_TRANSITION,
  95. R.styleable.Window_windowReenterTransition);
  96. mSharedElementEnterTransition = getTransition(mSharedElementEnterTransition, null,
  97. R.styleable.Window_windowSharedElementEnterTransition);
  98. mSharedElementReturnTransition = getTransition(mSharedElementReturnTransition,
  99. USE_DEFAULT_TRANSITION,
  100. R.styleable.Window_windowSharedElementReturnTransition);
  101. mSharedElementExitTransition = getTransition(mSharedElementExitTransition, null,
  102. R.styleable.Window_windowSharedElementExitTransition);
  103. mSharedElementReenterTransition = getTransition(mSharedElementReenterTransition,
  104. USE_DEFAULT_TRANSITION,
  105. R.styleable.Window_windowSharedElementReenterTransition);
  106. if (mAllowEnterTransitionOverlap == null) {
  107. mAllowEnterTransitionOverlap = getWindowStyle().getBoolean(
  108. R.styleable.Window_windowAllowEnterTransitionOverlap, true);
  109. }
  110. if (mAllowReturnTransitionOverlap == null) {
  111. mAllowReturnTransitionOverlap = getWindowStyle().getBoolean(
  112. R.styleable.Window_windowAllowReturnTransitionOverlap, true);
  113. }
  114. if (mBackgroundFadeDurationMillis < 0) {
  115. mBackgroundFadeDurationMillis = getWindowStyle().getInteger(
  116. R.styleable.Window_windowTransitionBackgroundFadeDuration,
  117. DEFAULT_BACKGROUND_FADE_DURATION_MS);
  118. }
  119. if (mSharedElementsUseOverlay == null) {
  120. mSharedElementsUseOverlay = getWindowStyle().getBoolean(
  121. R.styleable.Window_windowSharedElementsUseOverlay, true);
  122. }
  123. }
  124. }
  125. }

mDecor = generateDecor(-1)

  1. installDecor()中的第 4 行中,mDecor = generateDecor(-1);实例了一个DecorView对象mDecor
  1. protected DecorView generateDecor(int featureId) {
  2. // System process doesn't have application context and in that case we need to directly use
  3. // the context we have. Otherwise we want the application context, so we don't cling to the
  4. // activity.
  5. Context context;
  6. if (mUseDecorContext) {
  7. Context applicationContext = getContext().getApplicationContext();
  8. if (applicationContext == null) {
  9. context = getContext();
  10. } else {
  11. context = new DecorContext(applicationContext, getContext().getResources());
  12. if (mTheme != -1) {
  13. context.setTheme(mTheme);
  14. }
  15. }
  16. } else {
  17. context = getContext();
  18. }
  19. return new DecorView(context, featureId, this, getAttributes());//以new的方式实例出了一个DecorView对象
  20. }

并在installDecor()中的第 14 行中mContentParent = generateLayout(mDecor);把实例出来的mDecor对象带入后实例出了一个mContentParent 容器对象

mContentParent = generateLayout(mDecor)
方法内容总结:

获取有关Window的Style属性,是否浮窗(Floating)类型、主题(windowNoTitle与windowActionBar)、全屏(windowFullscreen)、Window透明情况等
对相关Window的Style属性设置requestFeature、setFlags等信息
根据 int features = getLocalFeatures();取得的features属性值,加载对应的DecorView布局容器(layoutResource)
NOTES:这里也验证了对requestFeature设置的属性,是在这里被使用到的,而这里是在setContentView流程中,所以requestFeature设置就必须在setContentView之前!
返回以features属性对应的DecorView布局容器中用来存放用户自定义的xml布局容器mContentParent对象
 

  1. protected ViewGroup generateLayout(DecorView decor) {
  2. // Apply data from current theme.
  3. //1.加载Window相关的Style属性:当我们在xml中设置一下Style属性之后,就是在这里进行加载
  4. TypedArray a = getWindowStyle();
  5. if (false) {
  6. System.out.println("From style:");
  7. String s = "Attrs:";
  8. for (int i = 0; i < R.styleable.Window.length; i++) {
  9. s = s + " " + Integer.toHexString(R.styleable.Window[i]) + "="
  10. + a.getString(i);
  11. }
  12. System.out.println(s);
  13. }
  14. //2.判断当前 Window 是不是浮窗类型的,比如 Dialog
  15. mIsFloating = a.getBoolean(R.styleable.Window_windowIsFloating, false);
  16. int flagsToUpdate = (FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR)
  17. & (~getForcedWindowFlags());
  18. if (mIsFloating) {
  19. setLayout(WRAP_CONTENT, WRAP_CONTENT);
  20. setFlags(0, flagsToUpdate);
  21. } else {
  22. setFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR, flagsToUpdate);
  23. }
  24. //3.设置 requestFeature、setFlags,处理设置的 Window 的主题Style属性值,并且 windowNoTitle 与 windowActionBar 互斥
  25. if (a.getBoolean(R.styleable.Window_windowNoTitle, false)) {
  26. requestFeature(FEATURE_NO_TITLE);
  27. } else if (a.getBoolean(R.styleable.Window_windowActionBar, false)) {
  28. // Don't allow an action bar if there is no title.
  29. requestFeature(FEATURE_ACTION_BAR);
  30. }
  31. if (a.getBoolean(R.styleable.Window_windowActionBarOverlay, false)) {
  32. requestFeature(FEATURE_ACTION_BAR_OVERLAY);
  33. }
  34. if (a.getBoolean(R.styleable.Window_windowActionModeOverlay, false)) {
  35. requestFeature(FEATURE_ACTION_MODE_OVERLAY);
  36. }
  37. if (a.getBoolean(R.styleable.Window_windowSwipeToDismiss, false)) {
  38. requestFeature(FEATURE_SWIPE_TO_DISMISS);
  39. }
  40. if (a.getBoolean(R.styleable.Window_windowFullscreen, false)) {
  41. setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN & (~getForcedWindowFlags()));
  42. }
  43. if (a.getBoolean(R.styleable.Window_windowTranslucentStatus,
  44. false)) {
  45. setFlags(FLAG_TRANSLUCENT_STATUS, FLAG_TRANSLUCENT_STATUS
  46. & (~getForcedWindowFlags()));
  47. }
  48. if (a.getBoolean(R.styleable.Window_windowTranslucentNavigation,
  49. false)) {
  50. setFlags(FLAG_TRANSLUCENT_NAVIGATION, FLAG_TRANSLUCENT_NAVIGATION
  51. & (~getForcedWindowFlags()));
  52. }
  53. if (a.getBoolean(R.styleable.Window_windowOverscan, false)) {
  54. setFlags(FLAG_LAYOUT_IN_OVERSCAN, FLAG_LAYOUT_IN_OVERSCAN&(~getForcedWindowFlags()));
  55. }
  56. if (a.getBoolean(R.styleable.Window_windowShowWallpaper, false)) {
  57. setFlags(FLAG_SHOW_WALLPAPER, FLAG_SHOW_WALLPAPER&(~getForcedWindowFlags()));
  58. }
  59. if (a.getBoolean(R.styleable.Window_windowEnableSplitTouch,
  60. getContext().getApplicationInfo().targetSdkVersion
  61. >= android.os.Build.VERSION_CODES.HONEYCOMB)) {
  62. setFlags(FLAG_SPLIT_TOUCH, FLAG_SPLIT_TOUCH&(~getForcedWindowFlags()));
  63. }
  64. a.getValue(R.styleable.Window_windowMinWidthMajor, mMinWidthMajor);
  65. a.getValue(R.styleable.Window_windowMinWidthMinor, mMinWidthMinor);
  66. if (DEBUG) Log.d(TAG, "Min width minor: " + mMinWidthMinor.coerceToString()
  67. + ", major: " + mMinWidthMajor.coerceToString());
  68. if (a.hasValue(R.styleable.Window_windowFixedWidthMajor)) {
  69. if (mFixedWidthMajor == null) mFixedWidthMajor = new TypedValue();
  70. a.getValue(R.styleable.Window_windowFixedWidthMajor,
  71. mFixedWidthMajor);
  72. }
  73. if (a.hasValue(R.styleable.Window_windowFixedWidthMinor)) {
  74. if (mFixedWidthMinor == null) mFixedWidthMinor = new TypedValue();
  75. a.getValue(R.styleable.Window_windowFixedWidthMinor,
  76. mFixedWidthMinor);
  77. }
  78. if (a.hasValue(R.styleable.Window_windowFixedHeightMajor)) {
  79. if (mFixedHeightMajor == null) mFixedHeightMajor = new TypedValue();
  80. a.getValue(R.styleable.Window_windowFixedHeightMajor,
  81. mFixedHeightMajor);
  82. }
  83. if (a.hasValue(R.styleable.Window_windowFixedHeightMinor)) {
  84. if (mFixedHeightMinor == null) mFixedHeightMinor = new TypedValue();
  85. a.getValue(R.styleable.Window_windowFixedHeightMinor,
  86. mFixedHeightMinor);
  87. }
  88. if (a.getBoolean(R.styleable.Window_windowContentTransitions, false)) {
  89. requestFeature(FEATURE_CONTENT_TRANSITIONS);
  90. }
  91. if (a.getBoolean(R.styleable.Window_windowActivityTransitions, false)) {
  92. requestFeature(FEATURE_ACTIVITY_TRANSITIONS);
  93. }
  94. //4.Window 是否透明属性
  95. mIsTranslucent = a.getBoolean(R.styleable.Window_windowIsTranslucent, false);
  96. final Context context = getContext();
  97. final int targetSdk = context.getApplicationInfo().targetSdkVersion;
  98. final boolean targetPreHoneycomb = targetSdk < android.os.Build.VERSION_CODES.HONEYCOMB;
  99. final boolean targetPreIcs = targetSdk < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
  100. final boolean targetPreL = targetSdk < android.os.Build.VERSION_CODES.LOLLIPOP;
  101. final boolean targetHcNeedsOptions = context.getResources().getBoolean(
  102. R.bool.target_honeycomb_needs_options_menu);
  103. final boolean noActionBar = !hasFeature(FEATURE_ACTION_BAR) || hasFeature(FEATURE_NO_TITLE);
  104. if (targetPreHoneycomb || (targetPreIcs && targetHcNeedsOptions && noActionBar)) {
  105. setNeedsMenuKey(WindowManager.LayoutParams.NEEDS_MENU_SET_TRUE);
  106. } else {
  107. setNeedsMenuKey(WindowManager.LayoutParams.NEEDS_MENU_SET_FALSE);
  108. }
  109. if (!mForcedStatusBarColor) {
  110. mStatusBarColor = a.getColor(R.styleable.Window_statusBarColor, 0xFF000000);
  111. }
  112. if (!mForcedNavigationBarColor) {
  113. mNavigationBarColor = a.getColor(R.styleable.Window_navigationBarColor, 0xFF000000);
  114. }
  115. WindowManager.LayoutParams params = getAttributes();
  116. // Non-floating windows on high end devices must put up decor beneath the system bars and
  117. // therefore must know about visibility changes of those.
  118. if (!mIsFloating && ActivityManager.isHighEndGfx()) {
  119. if (!targetPreL && a.getBoolean(
  120. R.styleable.Window_windowDrawsSystemBarBackgrounds,
  121. false)) {
  122. setFlags(FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS,
  123. FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS & ~getForcedWindowFlags());
  124. }
  125. if (mDecor.mForceWindowDrawsStatusBarBackground) {
  126. params.privateFlags |= PRIVATE_FLAG_FORCE_DRAW_STATUS_BAR_BACKGROUND;
  127. }
  128. }
  129. if (a.getBoolean(R.styleable.Window_windowLightStatusBar, false)) {
  130. decor.setSystemUiVisibility(
  131. decor.getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
  132. }
  133. if (mAlwaysReadCloseOnTouchAttr || getContext().getApplicationInfo().targetSdkVersion
  134. >= android.os.Build.VERSION_CODES.HONEYCOMB) {
  135. if (a.getBoolean(
  136. R.styleable.Window_windowCloseOnTouchOutside,
  137. false)) {
  138. setCloseOnTouchOutsideIfNotSet(true);
  139. }
  140. }
  141. if (!hasSoftInputMode()) {
  142. params.softInputMode = a.getInt(
  143. R.styleable.Window_windowSoftInputMode,
  144. params.softInputMode);
  145. }
  146. if (a.getBoolean(R.styleable.Window_backgroundDimEnabled,
  147. mIsFloating)) {
  148. /* All dialogs should have the window dimmed */
  149. if ((getForcedWindowFlags()&WindowManager.LayoutParams.FLAG_DIM_BEHIND) == 0) {
  150. params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
  151. }
  152. if (!haveDimAmount()) {
  153. params.dimAmount = a.getFloat(
  154. android.R.styleable.Window_backgroundDimAmount, 0.5f);
  155. }
  156. }
  157. if (params.windowAnimations == 0) {
  158. params.windowAnimations = a.getResourceId(
  159. R.styleable.Window_windowAnimationStyle, 0);
  160. }
  161. // The rest are only done if this window is not embedded; otherwise,
  162. // the values are inherited from our container.
  163. if (getContainer() == null) {
  164. if (mBackgroundDrawable == null) {
  165. if (mBackgroundResource == 0) {
  166. mBackgroundResource = a.getResourceId(
  167. R.styleable.Window_windowBackground, 0);
  168. }
  169. if (mFrameResource == 0) {
  170. mFrameResource = a.getResourceId(R.styleable.Window_windowFrame, 0);
  171. }
  172. mBackgroundFallbackResource = a.getResourceId(
  173. R.styleable.Window_windowBackgroundFallback, 0);
  174. if (false) {
  175. System.out.println("Background: "
  176. + Integer.toHexString(mBackgroundResource) + " Frame: "
  177. + Integer.toHexString(mFrameResource));
  178. }
  179. }
  180. if (mLoadElevation) {
  181. mElevation = a.getDimension(R.styleable.Window_windowElevation, 0);
  182. }
  183. mClipToOutline = a.getBoolean(R.styleable.Window_windowClipToOutline, false);
  184. mTextColor = a.getColor(R.styleable.Window_textColor, Color.TRANSPARENT);
  185. }
  186. // Inflate the window decor. 生成对应的 Window decor
  187. int layoutResource;
  188. //5.在这里获取设置好的feature属性值,然后根据features值初始化对应的DecorView容器布局,
  189. //同时说明在调用Window.requestFeature方法时,必须在setContentView之前,
  190. int features = getLocalFeatures();
  191. // System.out.println("Features: 0x" + Integer.toHexString(features));
  192. if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
  193. layoutResource = R.layout.screen_swipe_dismiss;
  194. setCloseOnSwipeEnabled(true);
  195. } else if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
  196. if (mIsFloating) {
  197. TypedValue res = new TypedValue();
  198. getContext().getTheme().resolveAttribute(
  199. R.attr.dialogTitleIconsDecorLayout, res, true);
  200. layoutResource = res.resourceId;
  201. } else {
  202. layoutResource = R.layout.screen_title_icons;
  203. }
  204. // XXX Remove this once action bar supports these features.
  205. removeFeature(FEATURE_ACTION_BAR);
  206. // System.out.println("Title Icons!");
  207. } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
  208. && (features & (1 << FEATURE_ACTION_BAR)) == 0) {
  209. // Special case for a window with only a progress bar (and title).
  210. // XXX Need to have a no-title version of embedded windows.
  211. layoutResource = R.layout.screen_progress;
  212. // System.out.println("Progress!");
  213. } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
  214. // Special case for a window with a custom title.
  215. // If the window is floating, we need a dialog layout
  216. if (mIsFloating) {
  217. TypedValue res = new TypedValue();
  218. getContext().getTheme().resolveAttribute(
  219. R.attr.dialogCustomTitleDecorLayout, res, true);
  220. layoutResource = res.resourceId;
  221. } else {
  222. layoutResource = R.layout.screen_custom_title;
  223. }
  224. // XXX Remove this once action bar supports these features.
  225. removeFeature(FEATURE_ACTION_BAR);
  226. } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
  227. // If no other features and not embedded, only need a title.
  228. // If the window is floating, we need a dialog layout
  229. if (mIsFloating) {
  230. TypedValue res = new TypedValue();
  231. getContext().getTheme().resolveAttribute(
  232. R.attr.dialogTitleDecorLayout, res, true);
  233. layoutResource = res.resourceId;
  234. } else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
  235. layoutResource = a.getResourceId(
  236. R.styleable.Window_windowActionBarFullscreenDecorLayout,
  237. R.layout.screen_action_bar);
  238. } else {
  239. layoutResource = R.layout.screen_title;
  240. }
  241. // System.out.println("Title!");
  242. } else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
  243. layoutResource = R.layout.screen_simple_overlay_action_mode;
  244. } else {
  245. // Embedded, so no decoration is needed.
  246. layoutResource = R.layout.screen_simple;
  247. // System.out.println("Simple!");
  248. }
  249. mDecor.startChanging();
  250. //加载DecorView布局文件
  251. mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
  252. //实例mDecor布局中id为content的容器:public static final int ID_ANDROID_CONTENT = com.android.internal.R.id.content;
  253. ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
  254. if (contentParent == null) {
  255. throw new RuntimeException("Window couldn't find content container view");
  256. }
  257. if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
  258. ProgressBar progress = getCircularProgressBar(false);
  259. if (progress != null) {
  260. progress.setIndeterminate(true);
  261. }
  262. }
  263. if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
  264. registerSwipeCallbacks(contentParent);
  265. }
  266. // Remaining setup -- of background and title -- that only applies
  267. // to top-level windows.
  268. if (getContainer() == null) {
  269. final Drawable background;
  270. if (mBackgroundResource != 0) {
  271. background = getContext().getDrawable(mBackgroundResource);
  272. } else {
  273. background = mBackgroundDrawable;
  274. }
  275. mDecor.setWindowBackground(background);
  276. final Drawable frame;
  277. if (mFrameResource != 0) {
  278. frame = getContext().getDrawable(mFrameResource);
  279. } else {
  280. frame = null;
  281. }
  282. mDecor.setWindowFrame(frame);
  283. mDecor.setElevation(mElevation);
  284. mDecor.setClipToOutline(mClipToOutline);
  285. if (mTitle != null) {
  286. setTitle(mTitle);
  287. }
  288. if (mTitleColor == 0) {
  289. mTitleColor = mTextColor;
  290. }
  291. setTitleColor(mTitleColor);
  292. }
  293. mDecor.finishChanging();
  294. return contentParent;
  295. }

到此,基于一开始抛出的Activity UI层级结构图便已清晰的深入剖析。并且得知了最后开发者在setContentView中设置的xml布局文件,最终都是被inflatedmContentParent这个ViewGroup中的。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/511705
推荐阅读
相关标签
  

闽ICP备14008679号