Android UI深度理解:Activity UI视图结构

2023-05-16

Activity UI视图结构

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

在这里插入图片描述

 源码分析

xml布局文件的使用

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

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

setContentView(R.layout.xxx)
 

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

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

android.view.PhoneWindow

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

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

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

@Override
public void setContentView(int layoutResID) {
    // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
    // decor, when theme attributes and the like are crystalized. Do not check the feature
    // before this happens.
    if (mContentParent == null) {
        installDecor();
    } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
        mContentParent.removeAllViews();
    }

    if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {//执行动画相关操作
        final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                getContext());
        transitionTo(newScene);
    } else {
    	//layoutResID是一个xml布局,它将在这里被添加到mContentParent这个容器中,最后进行View视图的显示
        mLayoutInflater.inflate(layoutResID, mContentParent);
    }
    mContentParent.requestApplyInsets();
    final Callback cb = getCallback();
    if (cb != null && !isDestroyed()) {
        cb.onContentChanged();
    }
    mContentParentExplicitlySet = true;
}

PhoneWindow的实例化过程

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

    final void attach(Context context, ActivityThread aThread,
            Instrumentation instr, IBinder token, int ident,
            Application application, Intent intent, ActivityInfo info,
            CharSequence title, Activity parent, String id,
            NonConfigurationInstances lastNonConfigurationInstances,
            Configuration config, String referrer, IVoiceInteractor voiceInteractor,
            Window window, ActivityConfigCallback activityConfigCallback) {
        attachBaseContext(context);

        mFragments.attachHost(null /*parent*/);
		//PhoneWindow 在这里被实例化出来了
        mWindow = new PhoneWindow(this, window, activityConfigCallback);
        mWindow.setWindowControllerCallback(this);
        mWindow.setCallback(this);
        mWindow.setOnWindowDismissedCallback(this);
        mWindow.getLayoutInflater().setPrivateFactory(this);
        ......
        /*并且在以下代码中,我们可以发现到Activity的相关生命周期的调用*/
        activity.mCalled = false;
        if (r.isPersistable()) {
            mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
        } else {
            mInstrumentation.callActivityOnCreate(activity, r.state);
        }
        if (!activity.mCalled) {
            throw new SuperNotCalledException(
                "Activity " + r.intent.getComponent().toShortString() +
                " did not call through to super.onCreate()");
        }
        r.activity = activity;
        r.stopped = true;
        if (!r.activity.mFinished) {
            activity.performStart();
            r.stopped = false;
        }
        if (!r.activity.mFinished) {
            if (r.isPersistable()) {
                if (r.state != null || r.persistentState != null) {
                    mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                            r.persistentState);
                }
            } else if (r.state != null) {
                mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
            }
        }
        if (!r.activity.mFinished) {
            activity.mCalled = false;
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnPostCreate(activity, r.state,
                        r.persistentState);
            } else {
                mInstrumentation.callActivityOnPostCreate(activity, r.state);
            }
            if (!activity.mCalled) {
                throw new SuperNotCalledException(
                    "Activity " + r.intent.getComponent().toShortString() +
                    " did not call through to super.onPostCreate()");
            }
        }
    }

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

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");

        ......
        Activity activity = null;
        ......

        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            ......

            if (activity != null) {
                ......
                appContext.setOuterContext(activity);
                //这里调用了Activity的attach方法,实现了PhoneWindow的初始化
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback);

                ......
            }
            r.paused = true;

            mActivities.put(r.token, r);

        } catch (SuperNotCalledException e) {
            throw e;

        } catch (Exception e) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to start activity " + component
                    + ": " + e.toString(), e);
            }
        }

        return activity;
    }

DecorView如何添加到Window窗口

在这里插入图片描述

关注点1:requestFeature(int featureId)

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

 

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

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

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

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

关注点3:mDecor
 

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

对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()

if (mContentParent == null) {
    installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
    mContentParent.removeAllViews();
}

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

private void installDecor() {
    mForceDecorInstall = false;
    if (mDecor == null) {
        mDecor = generateDecor(-1);//实例出一个DecorView对象
        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);

        // Set up decor part of UI to ignore fitsSystemWindows if appropriate.
        mDecor.makeOptionalFitsSystemWindows();

        final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById(
                R.id.decor_content_parent);

        if (decorContentParent != null) {
            mDecorContentParent = decorContentParent;
            mDecorContentParent.setWindowCallback(getCallback());
            if (mDecorContentParent.getTitle() == null) {
                mDecorContentParent.setWindowTitle(mTitle);
            }

            final int localFeatures = getLocalFeatures();
            for (int i = 0; i < FEATURE_MAX; i++) {
                if ((localFeatures & (1 << i)) != 0) {
                    mDecorContentParent.initFeature(i);
                }
            }

            mDecorContentParent.setUiOptions(mUiOptions);

            if ((mResourcesSetFlags & FLAG_RESOURCE_SET_ICON) != 0 ||
                    (mIconRes != 0 && !mDecorContentParent.hasIcon())) {
                mDecorContentParent.setIcon(mIconRes);
            } else if ((mResourcesSetFlags & FLAG_RESOURCE_SET_ICON) == 0 &&
                    mIconRes == 0 && !mDecorContentParent.hasIcon()) {
                mDecorContentParent.setIcon(
                        getContext().getPackageManager().getDefaultActivityIcon());
                mResourcesSetFlags |= FLAG_RESOURCE_SET_ICON_FALLBACK;
            }
            if ((mResourcesSetFlags & FLAG_RESOURCE_SET_LOGO) != 0 ||
                    (mLogoRes != 0 && !mDecorContentParent.hasLogo())) {
                mDecorContentParent.setLogo(mLogoRes);
            }

            // Invalidate if the panel menu hasn't been created before this.
            // Panel menu invalidation is deferred avoiding application onCreateOptionsMenu
            // being called in the middle of onCreate or similar.
            // A pending invalidation will typically be resolved before the posted message
            // would run normally in order to satisfy instance state restoration.
            PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
            if (!isDestroyed() && (st == null || st.menu == null) && !mIsStartingWindow) {
                invalidatePanelMenu(FEATURE_ACTION_BAR);
            }
        } else {
            mTitleView = findViewById(R.id.title);
            if (mTitleView != null) {
                if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) {
                    final View titleContainer = findViewById(R.id.title_container);
                    if (titleContainer != null) {
                        titleContainer.setVisibility(View.GONE);
                    } else {
                        mTitleView.setVisibility(View.GONE);
                    }
                    mContentParent.setForeground(null);
                } else {
                    mTitleView.setText(mTitle);
                }
            }
        }

        if (mDecor.getBackground() == null && mBackgroundFallbackResource != 0) {
            mDecor.setBackgroundFallback(mBackgroundFallbackResource);
        }

        // Only inflate or create a new TransitionManager if the caller hasn't
        // already set a custom one.
        if (hasFeature(FEATURE_ACTIVITY_TRANSITIONS)) {
            if (mTransitionManager == null) {
                final int transitionRes = getWindowStyle().getResourceId(
                        R.styleable.Window_windowContentTransitionManager,
                        0);
                if (transitionRes != 0) {
                    final TransitionInflater inflater = TransitionInflater.from(getContext());
                    mTransitionManager = inflater.inflateTransitionManager(transitionRes,
                            mContentParent);
                } else {
                    mTransitionManager = new TransitionManager();
                }
            }

            mEnterTransition = getTransition(mEnterTransition, null,
                    R.styleable.Window_windowEnterTransition);
            mReturnTransition = getTransition(mReturnTransition, USE_DEFAULT_TRANSITION,
                    R.styleable.Window_windowReturnTransition);
            mExitTransition = getTransition(mExitTransition, null,
                    R.styleable.Window_windowExitTransition);
            mReenterTransition = getTransition(mReenterTransition, USE_DEFAULT_TRANSITION,
                    R.styleable.Window_windowReenterTransition);
            mSharedElementEnterTransition = getTransition(mSharedElementEnterTransition, null,
                    R.styleable.Window_windowSharedElementEnterTransition);
            mSharedElementReturnTransition = getTransition(mSharedElementReturnTransition,
                    USE_DEFAULT_TRANSITION,
                    R.styleable.Window_windowSharedElementReturnTransition);
            mSharedElementExitTransition = getTransition(mSharedElementExitTransition, null,
                    R.styleable.Window_windowSharedElementExitTransition);
            mSharedElementReenterTransition = getTransition(mSharedElementReenterTransition,
                    USE_DEFAULT_TRANSITION,
                    R.styleable.Window_windowSharedElementReenterTransition);
            if (mAllowEnterTransitionOverlap == null) {
                mAllowEnterTransitionOverlap = getWindowStyle().getBoolean(
                        R.styleable.Window_windowAllowEnterTransitionOverlap, true);
            }
            if (mAllowReturnTransitionOverlap == null) {
                mAllowReturnTransitionOverlap = getWindowStyle().getBoolean(
                        R.styleable.Window_windowAllowReturnTransitionOverlap, true);
            }
            if (mBackgroundFadeDurationMillis < 0) {
                mBackgroundFadeDurationMillis = getWindowStyle().getInteger(
                        R.styleable.Window_windowTransitionBackgroundFadeDuration,
                        DEFAULT_BACKGROUND_FADE_DURATION_MS);
            }
            if (mSharedElementsUseOverlay == null) {
                mSharedElementsUseOverlay = getWindowStyle().getBoolean(
                        R.styleable.Window_windowSharedElementsUseOverlay, true);
            }
        }
    }
}

mDecor = generateDecor(-1)

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

并在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对象
 

protected ViewGroup generateLayout(DecorView decor) {
    // Apply data from current theme.

	//1.加载Window相关的Style属性:当我们在xml中设置一下Style属性之后,就是在这里进行加载
    TypedArray a = getWindowStyle();

    if (false) {
        System.out.println("From style:");
        String s = "Attrs:";
        for (int i = 0; i < R.styleable.Window.length; i++) {
            s = s + " " + Integer.toHexString(R.styleable.Window[i]) + "="
                    + a.getString(i);
        }
        System.out.println(s);
    }
	//2.判断当前 Window 是不是浮窗类型的,比如 Dialog
    mIsFloating = a.getBoolean(R.styleable.Window_windowIsFloating, false);
    int flagsToUpdate = (FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR)
            & (~getForcedWindowFlags());
    if (mIsFloating) {
        setLayout(WRAP_CONTENT, WRAP_CONTENT);
        setFlags(0, flagsToUpdate);
    } else {
        setFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR, flagsToUpdate);
    }
	//3.设置 requestFeature、setFlags,处理设置的 Window 的主题Style属性值,并且 windowNoTitle 与 windowActionBar 互斥
    if (a.getBoolean(R.styleable.Window_windowNoTitle, false)) {
        requestFeature(FEATURE_NO_TITLE);
    } else if (a.getBoolean(R.styleable.Window_windowActionBar, false)) {
        // Don't allow an action bar if there is no title.
        requestFeature(FEATURE_ACTION_BAR);
    }

    if (a.getBoolean(R.styleable.Window_windowActionBarOverlay, false)) {
        requestFeature(FEATURE_ACTION_BAR_OVERLAY);
    }

    if (a.getBoolean(R.styleable.Window_windowActionModeOverlay, false)) {
        requestFeature(FEATURE_ACTION_MODE_OVERLAY);
    }

    if (a.getBoolean(R.styleable.Window_windowSwipeToDismiss, false)) {
        requestFeature(FEATURE_SWIPE_TO_DISMISS);
    }

    if (a.getBoolean(R.styleable.Window_windowFullscreen, false)) {
        setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN & (~getForcedWindowFlags()));
    }

    if (a.getBoolean(R.styleable.Window_windowTranslucentStatus,
            false)) {
        setFlags(FLAG_TRANSLUCENT_STATUS, FLAG_TRANSLUCENT_STATUS
                & (~getForcedWindowFlags()));
    }

    if (a.getBoolean(R.styleable.Window_windowTranslucentNavigation,
            false)) {
        setFlags(FLAG_TRANSLUCENT_NAVIGATION, FLAG_TRANSLUCENT_NAVIGATION
                & (~getForcedWindowFlags()));
    }

    if (a.getBoolean(R.styleable.Window_windowOverscan, false)) {
        setFlags(FLAG_LAYOUT_IN_OVERSCAN, FLAG_LAYOUT_IN_OVERSCAN&(~getForcedWindowFlags()));
    }

    if (a.getBoolean(R.styleable.Window_windowShowWallpaper, false)) {
        setFlags(FLAG_SHOW_WALLPAPER, FLAG_SHOW_WALLPAPER&(~getForcedWindowFlags()));
    }

    if (a.getBoolean(R.styleable.Window_windowEnableSplitTouch,
            getContext().getApplicationInfo().targetSdkVersion
                    >= android.os.Build.VERSION_CODES.HONEYCOMB)) {
        setFlags(FLAG_SPLIT_TOUCH, FLAG_SPLIT_TOUCH&(~getForcedWindowFlags()));
    }

    a.getValue(R.styleable.Window_windowMinWidthMajor, mMinWidthMajor);
    a.getValue(R.styleable.Window_windowMinWidthMinor, mMinWidthMinor);
    if (DEBUG) Log.d(TAG, "Min width minor: " + mMinWidthMinor.coerceToString()
            + ", major: " + mMinWidthMajor.coerceToString());
    if (a.hasValue(R.styleable.Window_windowFixedWidthMajor)) {
        if (mFixedWidthMajor == null) mFixedWidthMajor = new TypedValue();
        a.getValue(R.styleable.Window_windowFixedWidthMajor,
                mFixedWidthMajor);
    }
    if (a.hasValue(R.styleable.Window_windowFixedWidthMinor)) {
        if (mFixedWidthMinor == null) mFixedWidthMinor = new TypedValue();
        a.getValue(R.styleable.Window_windowFixedWidthMinor,
                mFixedWidthMinor);
    }
    if (a.hasValue(R.styleable.Window_windowFixedHeightMajor)) {
        if (mFixedHeightMajor == null) mFixedHeightMajor = new TypedValue();
        a.getValue(R.styleable.Window_windowFixedHeightMajor,
                mFixedHeightMajor);
    }
    if (a.hasValue(R.styleable.Window_windowFixedHeightMinor)) {
        if (mFixedHeightMinor == null) mFixedHeightMinor = new TypedValue();
        a.getValue(R.styleable.Window_windowFixedHeightMinor,
                mFixedHeightMinor);
    }
    if (a.getBoolean(R.styleable.Window_windowContentTransitions, false)) {
        requestFeature(FEATURE_CONTENT_TRANSITIONS);
    }
    if (a.getBoolean(R.styleable.Window_windowActivityTransitions, false)) {
        requestFeature(FEATURE_ACTIVITY_TRANSITIONS);
    }
	//4.Window 是否透明属性
    mIsTranslucent = a.getBoolean(R.styleable.Window_windowIsTranslucent, false);

    final Context context = getContext();
    final int targetSdk = context.getApplicationInfo().targetSdkVersion;
    final boolean targetPreHoneycomb = targetSdk < android.os.Build.VERSION_CODES.HONEYCOMB;
    final boolean targetPreIcs = targetSdk < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
    final boolean targetPreL = targetSdk < android.os.Build.VERSION_CODES.LOLLIPOP;
    final boolean targetHcNeedsOptions = context.getResources().getBoolean(
            R.bool.target_honeycomb_needs_options_menu);
    final boolean noActionBar = !hasFeature(FEATURE_ACTION_BAR) || hasFeature(FEATURE_NO_TITLE);

    if (targetPreHoneycomb || (targetPreIcs && targetHcNeedsOptions && noActionBar)) {
        setNeedsMenuKey(WindowManager.LayoutParams.NEEDS_MENU_SET_TRUE);
    } else {
        setNeedsMenuKey(WindowManager.LayoutParams.NEEDS_MENU_SET_FALSE);
    }

    if (!mForcedStatusBarColor) {
        mStatusBarColor = a.getColor(R.styleable.Window_statusBarColor, 0xFF000000);
    }
    if (!mForcedNavigationBarColor) {
        mNavigationBarColor = a.getColor(R.styleable.Window_navigationBarColor, 0xFF000000);
    }

    WindowManager.LayoutParams params = getAttributes();

    // Non-floating windows on high end devices must put up decor beneath the system bars and
    // therefore must know about visibility changes of those.
    if (!mIsFloating && ActivityManager.isHighEndGfx()) {
        if (!targetPreL && a.getBoolean(
                R.styleable.Window_windowDrawsSystemBarBackgrounds,
                false)) {
            setFlags(FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS,
                    FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS & ~getForcedWindowFlags());
        }
        if (mDecor.mForceWindowDrawsStatusBarBackground) {
            params.privateFlags |= PRIVATE_FLAG_FORCE_DRAW_STATUS_BAR_BACKGROUND;
        }
    }
    if (a.getBoolean(R.styleable.Window_windowLightStatusBar, false)) {
        decor.setSystemUiVisibility(
                decor.getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
    }

    if (mAlwaysReadCloseOnTouchAttr || getContext().getApplicationInfo().targetSdkVersion
            >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        if (a.getBoolean(
                R.styleable.Window_windowCloseOnTouchOutside,
                false)) {
            setCloseOnTouchOutsideIfNotSet(true);
        }
    }

    if (!hasSoftInputMode()) {
        params.softInputMode = a.getInt(
                R.styleable.Window_windowSoftInputMode,
                params.softInputMode);
    }

    if (a.getBoolean(R.styleable.Window_backgroundDimEnabled,
            mIsFloating)) {
        /* All dialogs should have the window dimmed */
        if ((getForcedWindowFlags()&WindowManager.LayoutParams.FLAG_DIM_BEHIND) == 0) {
            params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
        }
        if (!haveDimAmount()) {
            params.dimAmount = a.getFloat(
                    android.R.styleable.Window_backgroundDimAmount, 0.5f);
        }
    }

    if (params.windowAnimations == 0) {
        params.windowAnimations = a.getResourceId(
                R.styleable.Window_windowAnimationStyle, 0);
    }

    // The rest are only done if this window is not embedded; otherwise,
    // the values are inherited from our container.
    if (getContainer() == null) {
        if (mBackgroundDrawable == null) {
            if (mBackgroundResource == 0) {
                mBackgroundResource = a.getResourceId(
                        R.styleable.Window_windowBackground, 0);
            }
            if (mFrameResource == 0) {
                mFrameResource = a.getResourceId(R.styleable.Window_windowFrame, 0);
            }
            mBackgroundFallbackResource = a.getResourceId(
                    R.styleable.Window_windowBackgroundFallback, 0);
            if (false) {
                System.out.println("Background: "
                        + Integer.toHexString(mBackgroundResource) + " Frame: "
                        + Integer.toHexString(mFrameResource));
            }
        }
        if (mLoadElevation) {
            mElevation = a.getDimension(R.styleable.Window_windowElevation, 0);
        }
        mClipToOutline = a.getBoolean(R.styleable.Window_windowClipToOutline, false);
        mTextColor = a.getColor(R.styleable.Window_textColor, Color.TRANSPARENT);
    }

    // Inflate the window decor. 生成对应的 Window decor

    int layoutResource;
    //5.在这里获取设置好的feature属性值,然后根据features值初始化对应的DecorView容器布局,
    //同时说明在调用Window.requestFeature方法时,必须在setContentView之前,
    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();
    //加载DecorView布局文件
    mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
	//实例mDecor布局中id为content的容器:public static final int ID_ANDROID_CONTENT = com.android.internal.R.id.content;
    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);
        }
    }

    if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
        registerSwipeCallbacks(contentParent);
    }

    // Remaining setup -- of background and title -- that only applies
    // to top-level windows.
    if (getContainer() == null) {
        final Drawable background;
        if (mBackgroundResource != 0) {
            background = getContext().getDrawable(mBackgroundResource);
        } else {
            background = mBackgroundDrawable;
        }
        mDecor.setWindowBackground(background);

        final Drawable frame;
        if (mFrameResource != 0) {
            frame = getContext().getDrawable(mFrameResource);
        } else {
            frame = null;
        }
        mDecor.setWindowFrame(frame);

        mDecor.setElevation(mElevation);
        mDecor.setClipToOutline(mClipToOutline);

        if (mTitle != null) {
            setTitle(mTitle);
        }

        if (mTitleColor == 0) {
            mTitleColor = mTextColor;
        }
        setTitleColor(mTitleColor);
    }

    mDecor.finishChanging();

    return contentParent;
}

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android UI深度理解:Activity UI视图结构 的相关文章

  • Android-Handler源码解析-Message

    成员变量 标识Message public int what 存储简单数据 xff0c 如果存储复杂的数据使用setData 方法 public int arg1 public int arg2 发送给接收者的任意对象 public Obj
  • Git中submodule的使用

    背景 面对比较复杂的项目 xff0c 我们有可能会将代码根据功能拆解成不同的子模块 主项目对子模块有依赖关系 xff0c 却又并不关心子模块的内部开发流程细节 这种情况下 xff0c 通常不会把所有源码都放在同一个 Git 仓库中 有一种比
  • Android-Handler源码解析-Looper

    成员变量 Log的TAG private static final String TAG 61 34 Looper 34 线程本地变量 xff0c 保证了每个线程仅有唯一的Looper对象 64 UnsupportedAppUsage st
  • 5步删除 git submodule

    1 删除submodule缓存 需要先暂存 gitmodules 文件 否则会报错 fatal please stage your changes to gitmodules or stash them to proceed 1 2 git
  • java.lang.NoSuchMethodError: java.lang.reflect.Field.trySetAccessible()Z

    把jdk 设置成11 就可以了
  • ES6 模块

    概述 在 ES6 前 xff0c 实现模块化使用的是 RequireJS 或者 seaJS xff08 分别是基于 AMD 规范的模块化库 xff0c 和基于 CMD 规范的模块化库 xff09 ES6 引入了模块化 xff0c 其设计思想
  • jdk 8 、9 10 11 12 13 14和 jdk 1.8 什么关系?

    jdk 8 就是 jdk 1 8 jdk9 就是 jdk 1 9
  • android studio设置jdk版本项目设置和全局设置

    android studio设置jdk版本项目设置和全局设置 方法1 xff1a 修改项目的gradle构建jdk xff08 建议在使用别人的单个项目时使用 xff09 打开项目设置 打开jdk设置 选择jdk11 注意要apply保存然
  • Gradle:执行命令时指定 JDK 版本

    应用场景 在命令行执行 Gradle 时使用的 Gradle 版本为系统环境变量中指定的 Gradle 版本 xff0c 使用的 JDK 为系统环境变量 JAVA HOME 指定的 JDK 来自 Gradle 官网的说明 xff1a JAV
  • Java基础-方法区以及static的内存分配图

    什么是方法区 xff1a 方法区是系统分配的一个内存逻辑区域 xff0c 是JVM在装载类文件时 xff0c 用于存储类型信息的 类的描述信息 方法区存放的信息包括 xff1a 类的基本信息 xff1a 1 每个类的全限定名 2 每个类的直
  • AudioManager 蓝牙sco连接相关接口

    蓝牙耳机连接之后 xff0c 发现音频发声的还是终端 xff0c 并没有转换到蓝牙耳机发声 网上搜索相关资料 xff0c 发现是蓝牙耳机需要建立链路来播放音频 简单介绍下蓝牙耳机的两种链路 xff1a A2DP xff08 异步链路 xff
  • Android 音频源码分析——AudioTrack设备选择

    基于Andorid9 0源码 以AudioTrack为例 xff0c 梳理下输出设备选择流程 音频设备选择的影响因素 xff1a AudioAttributes 声音流类型 setForceUse 设置 setPreferredDevice
  • 音频输出设备的选择

    场景 xff1a 使用AudioTrack播放一段音频 xff0c streamtype是AUDIO STREAM MUSIC xff1b 跟踪音频输出设备选择的流程 xff0c 代码会走到这里 xff1a 1 frameworks av
  • Engine::getDeviceForStrategyInt()解析

    audio devices t是int类型 audio devices t Engine getDeviceForStrategyInt routing strategy strategy DeviceVector availableOut
  • AudioService之音频输出通道切换

    前言 xff1a 音频输出的方式有很多种 xff0c 外放即扬声器 xff08 Speaker xff09 听筒 xff08 Telephone Receiver xff09 有线耳机 xff08 WiredHeadset xff09 蓝牙
  • UML 用例图以及UML的八种关系

    首先 xff0c 一张总体的知识脉络导图献上 xff1a 一 什么是用例图 xff1f 用例图描述了一组用例 参与者以及它们之间的关系 使用阶段 xff1a 软件需求分析 使用者 xff1a 软件分析人员 软件开发人员 用例模型 xff1a
  • 清除浏览器缓存后,发现页面样式不能加载了

    清除浏览器缓存后 xff0c 发现页面样式不能加载了 这里需要注意一个springboot版本问题 xff1a Spring Boot 1 x和2 x版本拦截器对于静态资源访问的区别 xff01 Spring Boot 1 x版本已经做好了
  • UML时序图(Sequence Diagram)

    什么是时序图 时序图 Sequence Diagram xff0c 又名序列图 循序图 xff0c 是一种UML交互图 它通过描述对象之间发送消息的时间顺序显示多个对象之间的动态协作 让我们来看一看visio2016对时序图的的解释 时序图
  • UML流程图

    流程图介绍 流程图 xff08 FlowChart xff09 是描述我们进行某一项活动所遵循顺序的一种图示方法 它能通过图形符号形象的表示解决问题的步骤和程序 好的流程图 xff0c 不仅能对我们的程序设计起到作用 xff1b 在帮助理解
  • Android: 如何切换 SCO 链路

    最近在做蓝牙音箱开发 xff0c 在 A2DP 和 HFP 来回切换的时候 xff0c 遇到了手机兼容性的问题 最终发现设备收声和手机收声 xff0c 是因为 soc 切换有问题 原先在网上找了一些资料发现其实还蛮简单的 就两句话 xff0

随机推荐

  • Java 枚举(enum) 详解6种常见的用法

    用法一 xff1a 常量 在JDK1 5 之前 xff0c 我们定义常量都是 xff1a public static final 现在好了 xff0c 有了枚举 xff0c 可以把相关的常量分组到一个枚举类型里 xff0c 而且枚举提供了比
  • Android注解快速入门和实用解析

    首先什么是注解 xff1f 64 Override就是注解 xff0c 它的作用是 xff1a 1 检查是否正确的重写了父类中的方法 2 标明代码 xff0c 这是一个重写的方法 1 体现在于 xff1a 检查子类重写的方法名与参数类型是否
  • Android高版本Service在后台一分钟被杀死

    最近公司出现了一个Bug xff0c Service在后台写log时候一分钟左右被杀死 xff0c 或者运行一会就被杀死了 xff0c 上网搜了一下原来是Android高版本为了保护电量 xff0c 流量什么的 xff0c 会在后台杀死这些
  • 解决Android8.0之后开启service

    背景 项目测试时发现的 xff0c 在双击返回键关闭应用后 xff08 并未杀死后台 xff09 重新打开APP xff0c 其他手机都OK xff0c 但是8 0的手机会出现较频繁的crash 检查代码 xff0c 问题锁定在重新开启应用
  • 在Android Studio中使用Lambda

    应用场景 在使用过程中 xff0c 不建议在自定义接口中使用 xff0c 原因是因为Lambda常应用在只有一个方法的接口中 而我们自定义的接口 xff0c 后期可能会增加接口中的方法 xff0c 这样修改的地方就比较多 xff0c 因为L
  • Android枚举实现Parcelable接口

    枚举类实现Parcelable的写法如下 xff1a public enum MyEnum implements Parcelable FIRST 1 SECOND 2 private int mValue MyEnum int value
  • Android Studio Build Output控制台输出乱码解决

    Android Studio版本升级到4 0之后 xff0c 出现Build Output控制台输出乱码的现象 该情况在Android Studio版本3 6及以上就会出现 解决方法 xff1a 点击Android Studio 菜单栏He
  • 1230---KVM Windows 虚拟机磁盘如何快速扩容

    KVM Windows 虚拟机磁盘如何快速扩容 前言 xff1a 由于KVM虚拟机直接构建于宿主机内核之上 xff0c 对于充分利用宿主机硬件性能有天然的优势 网上针对KVM Linux 虚拟机运维的文章很多 xff0c 但针对KVM Wi
  • Android中的IPv6

    什么是IPv6 IPv6 的全称是Internet Protocol version 6 Internet Protocol 译为 互联网协议 xff0c 所以 IPv6 就是互联网协议第6版 它对比于 IPv4 所带来的是地址池的扩容 x
  • 浅谈Android下的注解

    什么是注解 java lang annotation xff0c 接口 Annotation xff0c 在JDK5 0及以后版本引入 注解是代码里的特殊标记 xff0c 这些标记可以在编译 类加载 运行时被读取 xff0c 并执行相应的处
  • 浅析Java中的final关键字

    一 final关键字的基本用法 在Java中 xff0c final关键字可以用来修饰类 方法和变量 xff08 包括成员变量和局部变量 xff09 下面就从这三个方面来了解一下final关键字的基本用法 1 修饰类 当用final修饰一个
  • volatile与Java内存模型

    1 volatile特点 volatile的两大特点是可见性和有序性 xff1b volatile的内存语义 xff1a 当写一个volatile变量时 xff0c JMM会把该线程对应的本地内存中的共享变量值立即刷新回主内存中 当读一个v
  • 隐藏Detected problems with API compatibility警告弹窗

    如果在Android9 0亦即API 28或以上的系统中运行debug app时 xff0c 出现如下警告弹窗 xff1a Detected problems with API compatibility visit g co dev ap
  • JAVA中枚举如何保证线程安全

    枚举类型到底是什么类呢 xff1f 是enum吗 xff1f 明显不是 xff0c enum就和class一样 xff0c 只是一个关键字 xff0c 他并不是一个类 xff0c 那么枚举是由什么类维护的呢 xff0c 首先写一个简单的枚举
  • ‘sed‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件。

    在使用adb命令查看task和Activity的时候 xff0c 发现报错 sed 不是内部或外部命令 xff0c 也不是可运行的程序 或批处理文件 看样子是没有配置sed的环境变量 xff0c 或者没有sed工具 从网上找了一下 xff0
  • win11 我们无法设置移动热点

    有可能是因为Windows移动热点服务被禁用 启动移动热点服务 1 使用该配件的键 43 热键启动运行 WindowsR 2 要打开 服务 xff0c 请在 打开 框中键入此文本并单击 确定 xff1a services msc 3 选中W
  • 链栈(java 实现)

    Node类 xff1a package LinkStack public class Node String name int age Node next public Node public Node String name int ag
  • Android之WindowManager介绍

    WindowManager android中真正展示给用户的是window和view activity在android中所其的作用主要是处理一些逻辑问题 xff0c 比如生命周期的管理 建立窗口等 在android中 xff0c 窗口的管理
  • https://dl.bintray.com/umsdk/release/com/facebook/react/react-native/maven-metadata 502 Bad Gateway

    https dl bintray com umsdk release com facebook react react native maven metadata xml 39 Received status code 502 from s
  • Android UI深度理解:Activity UI视图结构

    Activity UI视图结构 每个Activity都会获得一个窗口 xff0c 那就是Window xff0c 它用于绘制用户的UI界面 Window是一个抽象类 xff0c 提供了绘制窗口的一组通用API xff0c PhoneWind