Android Activity、window、View的关系

1.三者的关系

Activity管理window,window管理view

751864021fe54a97903539be7942cc51.png

 从上图可以看出Activity包含Window,Window包含View。

2.源码分析

Activity.java:

public class Activity extends ContextThemeWrapper implements LayoutInflater.Factory2, Window.Callback, KeyEvent.Callback,OnCreateContextMenuListener, ComponentCallbacks2, Window.OnWindowDismissedCallback, WindowControllerCallback, AutofillManager.AutofillClient {

     ....

    private Window 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*/);

  // Window类是个抽象类,实现类是PhoneWindow

        mWindow = new PhoneWindow(this, window, activityConfigCallback); 

      mWindow.setWindowControllerCallback(this);

        mWindow.setCallback(this);

        mWindow.setOnWindowDismiss edCallback(this);

        mWindow.getLayoutInflater().setPrivateFa ctory(this);

        ....        

    }

 ....

}

从Activity源码中可以看到,在attach方法中创建了Window的实现类PhoneWindow。

PhoneWindow.java:

public PhoneWindow(Context context, Window preservedWindow, ActivityConfigCallback activityConfigCallback) {

    this(context);

    // Only main activity windows use decor context, all the other windows depend on whatever context that was given to them.

    mUseDecorContext = true;

    if (preservedWindow != null) {

        mDecor = (DecorView) preservedWindow.getDecorView();

        mElevation = preservedWindow.getElevation();

        mLoadElevation = false;

        mForceDecorInstall = true;

        getAttributes().token = preservedWindow.getAttributes().token;

    }

    boolean forceResizable = Settings.Global.getInt(context.getContentResolver(),DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;

    mSupportsPictureInPicture = forceResizable ||context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE);

    mActivityConfigCallback = activityConfigCallback;

}

在PhoneWindow的构造方法中有获取DecorView。

因此,可以看出:Activity持有Window对象(实现类是PhoneWindow);PhoneWindow构造方法中获取DecorView。

猜你喜欢

转载自blog.csdn.net/zenmela2011/article/details/125014281