学习android Activity的setContentView

来源:互联网 发布:移动宽带网络加速器 编辑:程序博客网 时间:2024/05/16 06:35
setContentView
  1. public void setContentView(@LayoutRes int layoutResID) {
  2. getWindow().setContentView(layoutResID);
  3. initWindowDecorActionBar();
  4. }
getWindow().setContentView(layoutResID);Window中
  1. public abstract void setContentView(@LayoutRes int layoutResID);
window 的父类是 PhoneWindow
去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. mLayoutInflater.inflate(layoutResID, mContentParent);
  17. }
  18. mContentParent.requestApplyInsets();
  19. final Callback cb = getCallback();
  20. if (cb != null && !isDestroyed()) {
  21. cb.onContentChanged();
  22. }
  23. mContentParentExplicitlySet = true;
  24. }

查看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); //根据mDecor得到mContentParent
  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 = (TextView) 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. }
查看generateDecor()方法 返回一个DecorView对象
  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; //获取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());
  20. }
查看generateLayout()方法 就是返回一个ViewGroup加入到DecorView中
  1. protected ViewGroup generateLayout(DecorView decor) {
  2. // Apply data from current theme.
  3. TypedArray a = getWindowStyle();
  4. if (false) {
  5. System.out.println("From style:");
  6. String s = "Attrs:";
  7. for (int i = 0; i < R.styleable.Window.length; i++) {
  8. s = s + " " + Integer.toHexString(R.styleable.Window[i]) + "="
  9. + a.getString(i);
  10. }
  11. System.out.println(s);
  12. }
  13. mIsFloating = a.getBoolean(R.styleable.Window_windowIsFloating, false);
  14. int flagsToUpdate = (FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR)
  15. & (~getForcedWindowFlags());
  16. if (mIsFloating) {
  17. setLayout(WRAP_CONTENT, WRAP_CONTENT);
  18. setFlags(0, flagsToUpdate);
  19. } else {
  20. setFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR, flagsToUpdate);
  21. }
  22. if (a.getBoolean(R.styleable.Window_windowNoTitle, false)) {
  23. requestFeature(FEATURE_NO_TITLE);
  24. } else if (a.getBoolean(R.styleable.Window_windowActionBar, false)) {
  25. // Don't allow an action bar if there is no title.
  26. requestFeature(FEATURE_ACTION_BAR);
  27. }
  28. if (a.getBoolean(R.styleable.Window_windowActionBarOverlay, false)) {
  29. requestFeature(FEATURE_ACTION_BAR_OVERLAY);
  30. }
  31. if (a.getBoolean(R.styleable.Window_windowActionModeOverlay, false)) {
  32. requestFeature(FEATURE_ACTION_MODE_OVERLAY);
  33. }
  34. if (a.getBoolean(R.styleable.Window_windowSwipeToDismiss, false)) {
  35. requestFeature(FEATURE_SWIPE_TO_DISMISS);
  36. }
  37. if (a.getBoolean(R.styleable.Window_windowFullscreen, false)) {
  38. setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN & (~getForcedWindowFlags()));
  39. }
  40. if (a.getBoolean(R.styleable.Window_windowTranslucentStatus,
  41. false)) {
  42. setFlags(FLAG_TRANSLUCENT_STATUS, FLAG_TRANSLUCENT_STATUS
  43. & (~getForcedWindowFlags()));
  44. }
  45. if (a.getBoolean(R.styleable.Window_windowTranslucentNavigation,
  46. false)) {
  47. setFlags(FLAG_TRANSLUCENT_NAVIGATION, FLAG_TRANSLUCENT_NAVIGATION
  48. & (~getForcedWindowFlags()));
  49. }
  50. if (a.getBoolean(R.styleable.Window_windowOverscan, false)) {
  51. setFlags(FLAG_LAYOUT_IN_OVERSCAN, FLAG_LAYOUT_IN_OVERSCAN&(~getForcedWindowFlags()));
  52. }
  53. if (a.getBoolean(R.styleable.Window_windowShowWallpaper, false)) {
  54. setFlags(FLAG_SHOW_WALLPAPER, FLAG_SHOW_WALLPAPER&(~getForcedWindowFlags()));
  55. }
  56. if (a.getBoolean(R.styleable.Window_windowEnableSplitTouch,
  57. getContext().getApplicationInfo().targetSdkVersion
  58. >= android.os.Build.VERSION_CODES.HONEYCOMB)) {
  59. setFlags(FLAG_SPLIT_TOUCH, FLAG_SPLIT_TOUCH&(~getForcedWindowFlags()));
  60. }
  61. a.getValue(R.styleable.Window_windowMinWidthMajor, mMinWidthMajor);
  62. a.getValue(R.styleable.Window_windowMinWidthMinor, mMinWidthMinor);
  63. if (DEBUG) Log.d(TAG, "Min width minor: " + mMinWidthMinor.coerceToString()
  64. + ", major: " + mMinWidthMajor.coerceToString());
  65. if (a.hasValue(R.styleable.Window_windowFixedWidthMajor)) {
  66. if (mFixedWidthMajor == null) mFixedWidthMajor = new TypedValue();
  67. a.getValue(R.styleable.Window_windowFixedWidthMajor,
  68. mFixedWidthMajor);
  69. }
  70. if (a.hasValue(R.styleable.Window_windowFixedWidthMinor)) {
  71. if (mFixedWidthMinor == null) mFixedWidthMinor = new TypedValue();
  72. a.getValue(R.styleable.Window_windowFixedWidthMinor,
  73. mFixedWidthMinor);
  74. }
  75. if (a.hasValue(R.styleable.Window_windowFixedHeightMajor)) {
  76. if (mFixedHeightMajor == null) mFixedHeightMajor = new TypedValue();
  77. a.getValue(R.styleable.Window_windowFixedHeightMajor,
  78. mFixedHeightMajor);
  79. }
  80. if (a.hasValue(R.styleable.Window_windowFixedHeightMinor)) {
  81. if (mFixedHeightMinor == null) mFixedHeightMinor = new TypedValue();
  82. a.getValue(R.styleable.Window_windowFixedHeightMinor,
  83. mFixedHeightMinor);
  84. }
  85. if (a.getBoolean(R.styleable.Window_windowContentTransitions, false)) {
  86. requestFeature(FEATURE_CONTENT_TRANSITIONS);
  87. }
  88. if (a.getBoolean(R.styleable.Window_windowActivityTransitions, false)) {
  89. requestFeature(FEATURE_ACTIVITY_TRANSITIONS);
  90. }
  91. mIsTranslucent = a.getBoolean(R.styleable.Window_windowIsTranslucent, false);
  92. final Context context = getContext();
  93. final int targetSdk = context.getApplicationInfo().targetSdkVersion;
  94. final boolean targetPreHoneycomb = targetSdk < android.os.Build.VERSION_CODES.HONEYCOMB;
  95. final boolean targetPreIcs = targetSdk < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
  96. final boolean targetPreL = targetSdk < android.os.Build.VERSION_CODES.LOLLIPOP;
  97. final boolean targetHcNeedsOptions = context.getResources().getBoolean(
  98. R.bool.target_honeycomb_needs_options_menu);
  99. final boolean noActionBar = !hasFeature(FEATURE_ACTION_BAR) || hasFeature(FEATURE_NO_TITLE);
  100. if (targetPreHoneycomb || (targetPreIcs && targetHcNeedsOptions && noActionBar)) {
  101. setNeedsMenuKey(WindowManager.LayoutParams.NEEDS_MENU_SET_TRUE);
  102. } else {
  103. setNeedsMenuKey(WindowManager.LayoutParams.NEEDS_MENU_SET_FALSE);
  104. }
  105. if (!mForcedStatusBarColor) {
  106. mStatusBarColor = a.getColor(R.styleable.Window_statusBarColor, 0xFF000000);
  107. }
  108. if (!mForcedNavigationBarColor) {
  109. mNavigationBarColor = a.getColor(R.styleable.Window_navigationBarColor, 0xFF000000);
  110. }
  111. WindowManager.LayoutParams params = getAttributes();
  112. // Non-floating windows on high end devices must put up decor beneath the system bars and
  113. // therefore must know about visibility changes of those.
  114. if (!mIsFloating && ActivityManager.isHighEndGfx()) {
  115. if (!targetPreL && a.getBoolean(
  116. R.styleable.Window_windowDrawsSystemBarBackgrounds,
  117. false)) {
  118. setFlags(FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS,
  119. FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS & ~getForcedWindowFlags());
  120. }
  121. if (mDecor.mForceWindowDrawsStatusBarBackground) {
  122. params.privateFlags |= PRIVATE_FLAG_FORCE_DRAW_STATUS_BAR_BACKGROUND;
  123. }
  124. }
  125. if (a.getBoolean(R.styleable.Window_windowLightStatusBar, false)) {
  126. decor.setSystemUiVisibility(
  127. decor.getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
  128. }
  129. if (mAlwaysReadCloseOnTouchAttr || getContext().getApplicationInfo().targetSdkVersion
  130. >= android.os.Build.VERSION_CODES.HONEYCOMB) {
  131. if (a.getBoolean(
  132. R.styleable.Window_windowCloseOnTouchOutside,
  133. false)) {
  134. setCloseOnTouchOutsideIfNotSet(true);
  135. }
  136. }
  137. if (!hasSoftInputMode()) {
  138. params.softInputMode = a.getInt(
  139. R.styleable.Window_windowSoftInputMode,
  140. params.softInputMode);
  141. }
  142. if (a.getBoolean(R.styleable.Window_backgroundDimEnabled,
  143. mIsFloating)) {
  144. /* All dialogs should have the window dimmed */
  145. if ((getForcedWindowFlags()&WindowManager.LayoutParams.FLAG_DIM_BEHIND) == 0) {
  146. params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
  147. }
  148. if (!haveDimAmount()) {
  149. params.dimAmount = a.getFloat(
  150. android.R.styleable.Window_backgroundDimAmount, 0.5f);
  151. }
  152. }
  153. if (params.windowAnimations == 0) {
  154. params.windowAnimations = a.getResourceId(
  155. R.styleable.Window_windowAnimationStyle, 0);
  156. }
  157. // The rest are only done if this window is not embedded; otherwise,
  158. // the values are inherited from our container.
  159. if (getContainer() == null) {
  160. if (mBackgroundDrawable == null) {
  161. if (mBackgroundResource == 0) {
  162. mBackgroundResource = a.getResourceId(
  163. R.styleable.Window_windowBackground, 0);
  164. }
  165. if (mFrameResource == 0) {
  166. mFrameResource = a.getResourceId(R.styleable.Window_windowFrame, 0);
  167. }
  168. mBackgroundFallbackResource = a.getResourceId(
  169. R.styleable.Window_windowBackgroundFallback, 0);
  170. if (false) {
  171. System.out.println("Background: "
  172. + Integer.toHexString(mBackgroundResource) + " Frame: "
  173. + Integer.toHexString(mFrameResource));
  174. }
  175. }
  176. if (mLoadElevation) {
  177. mElevation = a.getDimension(R.styleable.Window_windowElevation, 0);
  178. }
  179. mClipToOutline = a.getBoolean(R.styleable.Window_windowClipToOutline, false);
  180. mTextColor = a.getColor(R.styleable.Window_textColor, Color.TRANSPARENT);
  181. }
  182. // Inflate the window decor.
  183. int layoutResource;
  184. int features = getLocalFeatures();
  185. // System.out.println("Features: 0x" + Integer.toHexString(features));
  186. if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
  187. layoutResource = R.layout.screen_swipe_dismiss;
  188. } else if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
  189. if (mIsFloating) {
  190. TypedValue res = new TypedValue();
  191. getContext().getTheme().resolveAttribute(
  192. R.attr.dialogTitleIconsDecorLayout, res, true);
  193. layoutResource = res.resourceId;
  194. } else {
  195. layoutResource = R.layout.screen_title_icons;
  196. }
  197. // XXX Remove this once action bar supports these features.
  198. removeFeature(FEATURE_ACTION_BAR);
  199. // System.out.println("Title Icons!");
  200. } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
  201. && (features & (1 << FEATURE_ACTION_BAR)) == 0) {
  202. // Special case for a window with only a progress bar (and title).
  203. // XXX Need to have a no-title version of embedded windows.
  204. layoutResource = R.layout.screen_progress;
  205. // System.out.println("Progress!");
  206. } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
  207. // Special case for a window with a custom title.
  208. // If the window is floating, we need a dialog layout
  209. if (mIsFloating) {
  210. TypedValue res = new TypedValue();
  211. getContext().getTheme().resolveAttribute(
  212. R.attr.dialogCustomTitleDecorLayout, res, true);
  213. layoutResource = res.resourceId;
  214. } else {
  215. layoutResource = R.layout.screen_custom_title;
  216. }
  217. // XXX Remove this once action bar supports these features.
  218. removeFeature(FEATURE_ACTION_BAR);
  219. } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
  220. // If no other features and not embedded, only need a title.
  221. // If the window is floating, we need a dialog layout
  222. if (mIsFloating) {
  223. TypedValue res = new TypedValue();
  224. getContext().getTheme().resolveAttribute(
  225. R.attr.dialogTitleDecorLayout, res, true);
  226. layoutResource = res.resourceId;
  227. } else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
  228. layoutResource = a.getResourceId(
  229. R.styleable.Window_windowActionBarFullscreenDecorLayout,
  230. R.layout.screen_action_bar);
  231. } else {
  232. layoutResource = R.layout.screen_title;
  233. }
  234. // System.out.println("Title!");
  235. } else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
  236. layoutResource = R.layout.screen_simple_overlay_action_mode;
  237. } else {
  238. // Embedded, so no decoration is needed.
  239. layoutResource = R.layout.screen_simple;
  240. // System.out.println("Simple!");
  241. }
  242. mDecor.startChanging();
  243. mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
  244. ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
  245. if (contentParent == null) {
  246. throw new RuntimeException("Window couldn't find content container view");
  247. }
  248. if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
  249. ProgressBar progress = getCircularProgressBar(false);
  250. if (progress != null) {
  251. progress.setIndeterminate(true);
  252. }
  253. }
  254. if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
  255. registerSwipeCallbacks();
  256. }
  257. // Remaining setup -- of background and title -- that only applies
  258. // to top-level windows.
  259. if (getContainer() == null) {
  260. final Drawable background;
  261. if (mBackgroundResource != 0) {
  262. background = getContext().getDrawable(mBackgroundResource);
  263. } else {
  264. background = mBackgroundDrawable;
  265. }
  266. mDecor.setWindowBackground(background);
  267. final Drawable frame;
  268. if (mFrameResource != 0) {
  269. frame = getContext().getDrawable(mFrameResource);
  270. } else {
  271. frame = null;
  272. }
  273. mDecor.setWindowFrame(frame);
  274. mDecor.setElevation(mElevation);
  275. mDecor.setClipToOutline(mClipToOutline);
  276. if (mTitle != null) {
  277. setTitle(mTitle);
  278. }
  279. if (mTitleColor == 0) {
  280. mTitleColor = mTextColor;
  281. }
  282. setTitleColor(mTitleColor);
  283. }
  284. mDecor.finishChanging();
  285. return contentParent;
  286. }
查看mLayoutInflater.inflate(layoutResID, mContentParent);
  1. public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
  2. return inflate(resource, root, root != null);
  3. }
  1. public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
  2. final Resources res = getContext().getResources();
  3. if (DEBUG) {
  4. Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
  5. + Integer.toHexString(resource) + ")");
  6. }
  7. final XmlResourceParser parser = res.getLayout(resource);
  8. try {
  9. return inflate(parser, root, attachToRoot); //把XML文件转换为对象
  10. } finally {
  11. parser.close();
  12. }
  13. }
  1. public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
  2. synchronized (mConstructorArgs) {
  3. Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
  4. final Context inflaterContext = mContext;
  5. final AttributeSet attrs = Xml.asAttributeSet(parser);
  6. Context lastContext = (Context) mConstructorArgs[0];
  7. mConstructorArgs[0] = inflaterContext;
  8. View result = root;
  9. try {
  10. // Look for the root node.
  11. int type;
  12. while ((type = parser.next()) != XmlPullParser.START_TAG &&
  13. type != XmlPullParser.END_DOCUMENT) {
  14. // Empty
  15. }
  16. if (type != XmlPullParser.START_TAG) {
  17. throw new InflateException(parser.getPositionDescription()
  18. + ": No start tag found!");
  19. }
  20. final String name = parser.getName();
  21. if (DEBUG) {
  22. System.out.println("**************************");
  23. System.out.println("Creating root view: "
  24. + name);
  25. System.out.println("**************************");
  26. }
  27. if (TAG_MERGE.equals(name)) {
  28. if (root == null || !attachToRoot) {
  29. throw new InflateException("<merge /> can be used only with a valid "
  30. + "ViewGroup root and attachToRoot=true");
  31. }
  32. rInflate(parser, root, inflaterContext, attrs, false);
  33. } else {
  34. // Temp is the root view that was found in the xml
  35. final View temp = createViewFromTag(root, name, inflaterContext, attrs);
  36. ViewGroup.LayoutParams params = null;
  37. if (root != null) {
  38. if (DEBUG) {
  39. System.out.println("Creating params from root: " +
  40. root);
  41. }
  42. // Create layout params that match root, if supplied
  43. params = root.generateLayoutParams(attrs);
  44. if (!attachToRoot) {
  45. // Set the layout params for temp if we are not
  46. // attaching. (If we are, we use addView, below)
  47. temp.setLayoutParams(params);
  48. }
  49. }
  50. if (DEBUG) {
  51. System.out.println("-----> start inflating children");
  52. }
  53. // Inflate all children under temp against its context.
  54. rInflateChildren(parser, temp, attrs, true);
  55. if (DEBUG) {
  56. System.out.println("-----> done inflating children");
  57. }
  58. // We are supposed to attach all the views we found (int temp)
  59. // to root. Do that now.
  60. if (root != null && attachToRoot) {
  61. root.addView(temp, params);
  62. }
  63. // Decide whether to return the root that was passed in or the
  64. // top view found in xml.
  65. if (root == null || !attachToRoot) {
  66. result = temp;
  67. }
  68. }
  69. } catch (XmlPullParserException e) {
  70. final InflateException ie = new InflateException(e.getMessage(), e);
  71. ie.setStackTrace(EMPTY_STACK_TRACE);
  72. throw ie;
  73. } catch (Exception e) {
  74. final InflateException ie = new InflateException(parser.getPositionDescription()
  75. + ": " + e.getMessage(), e);
  76. ie.setStackTrace(EMPTY_STACK_TRACE);
  77. throw ie;
  78. } finally {
  79. // Don't retain static reference on context.
  80. mConstructorArgs[0] = lastContext;
  81. mConstructorArgs[1] = null;
  82. Trace.traceEnd(Trace.TRACE_TAG_VIEW);
  83. }
  84. return result;
  85. }
  86. }





原创粉丝点击