【Android开发】 Activity构成

本文深入解析了Android中Activity如何加载布局,从setContentView()开始,探讨了PhoneWindow、DecorView和ContentView的生成过程,详细解释了事件分发机制前的准备工作,包括View的层级结构和布局资源的解析。通过示例代码展示了如何遍历布局找到根View,进一步巩固了理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Activity构成

在自定义 View 的时候,需要去了解 View 体系的一个非常重要的知识点—— View 的事件分发机制。在讲 View 的事件分发机制之前,需要先了解一下 Activity 的构成,因为当你点击一个 View 时,会产生点击事件,点击事件最先传递到 Activity

先来看 Activity 是怎么加载布局的:

    public void setContentView(@LayoutRes int layoutResID) {
   
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }

当你加载一个布局的时候,Activity 会先调用 getWindow().setContentView(layoutResID),再往下看什么是 getWindow()

    public Window getWindow() {
   
        return mWindow;
    }

getWindow() 返回了 mWindow,继续往下找,会在 Activityattach() 方法中发现使用了 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, IBinder assistToken) {
   
        attachBaseContext(context);

        mFragments.attachHost(null /*parent*/);

        mWindow = new PhoneWindow(this, window, activityConfigCallback);
        mWindow.setWindowControllerCallback(this);
        mWindow.setCallback(this);
        mWindow.setOnWindowDismissedCallback(this);
        mWindow.getLayoutInflater().setPrivateFactory(this);
        
        ···
    }

getWindow() 返回了 mWindow,而 mWindow 又是由 PhoneWindow 实例化而来的。所以 getWindow().setContentView() 实际上就是指的是 PhonewWindow.setContentView(),接下来看看 PhonewWindow.setContentView() 的内容:

    @Override
    public void setContentView(int layoutResID) {
   
        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 {
   
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        mContentParent.requestApplyInsets();
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hovf-1120

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值