一起Talk Android吧(第一百一十五回:Android中View的助手二)

本文深入探讨了Android中DecorView的重要角色,作为所有View的根节点,它支撑起了整个UI布局的基础。文章通过源代码解析了DecorView的创建过程,从setContentView到generateDecor,揭示了其背后的工作原理。

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

各位看官们,大家好,上一回中咱们说的是Android中View助手的例子,这一回咱们继续说该例子。闲话休提,言归正转。让我们一起Talk Android吧!

看官们,我们这一回介绍View的另外一位助手:DecorView。它可以看作是所有View的根,因为View及其控件都是建立在它的基础上的。接下来我们通过代码结合文字的方式来演示它是如何被创建的。

首先还是回到setContenView函数中,下面是它的源代码:

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

我们在上回中介绍过,getWindow返回的是PhoneWindow类型的对象,因此我们看看PhoneWindow类中setContentView的实现:

    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();
        }
           //其它的代码省略
    }

我们重点看看installDecor函数,DecorView就是通过它间接创建的,详细可以看下面的源代码:

    private void installDecor() {
        mForceDecorInstall = false;
        if (mDecor == null) {
            mDecor = generateDecor(-1);
           //其它的代码省略
    }

代码中直接创建DecorView的就是generateDecor函数,下面是它的具体实现:

    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.
        //其它的代码省略
        return new DecorView(context, featureId, this, getAttributes());
    }

各位看官,关于Androd中View助手的例子咱们就介绍到这里,欲知后面还有什么例子,且听下回分解!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

talk_8

真诚赞赏,手有余香

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

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

打赏作者

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

抵扣说明:

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

余额充值