windowIsTranslucent与windowBackground爱恨情仇

 

涉及知识点:Activity、Window、Dialog、View 关联

前言:今天有人问我一个问题(如下)。秉着分享使我快乐的原则,在解决问题后,作此篇

问题:

windowBackground为透明时, windowIsTranslucent为false, Activity背景为何还是黑色,为什么不是透明?
windowBackground为红色时, windowIsTranslucent为true, Activity背景还是红色,为什么不是透明?

解决:

1、单刀直入核心主题:
windowBackground 、windowIsTranslucent顾名思义是Window属性,但是具体的实现是在哪里呢?是在RootView中---------也就是DecorView类中
1、我们进入DecorView类中:
2、找到setWindowBackground方法

public void setWindowBackground(Drawable drawable) {
    if (getBackground() != drawable) {
        setBackgroundDrawable(drawable);
        if (drawable != null) {
            mResizingBackgroundDrawable = enforceNonTranslucentBackground(drawable,
                    mWindow.isTranslucent() || mWindow.isShowingWallpaper());
        } else {
            mResizingBackgroundDrawable = getResizingBackgroundDrawable(
                    getContext(), 0, mWindow.mBackgroundFallbackResource,
                    mWindow.isTranslucent() || mWindow.isShowingWallpaper());
        }
        if (mResizingBackgroundDrawable != null) {
            mResizingBackgroundDrawable.getPadding(mBackgroundPadding);
        } else {
            mBackgroundPadding.setEmpty();
        }
        drawableChanged();
    }
}

我们可以看到enforceNonTranslucentBackground中使用到 Window.isTranslucent(),于是我们向下进一步寻找

3、找到 enforceNonTranslucentBackground

/**
 * Enforces a drawable to be non-translucent to act as a background if needed, i.e. if the
 * window is not translucent.
 */
private static Drawable enforceNonTranslucentBackground(Drawable drawable,
        boolean windowTranslucent) {
    if (!windowTranslucent && drawable instanceof ColorDrawable) {
        ColorDrawable colorDrawable = (ColorDrawable) drawable;
        int color = colorDrawable.getColor();
        if (Color.alpha(color) != 255) {
            ColorDrawable copy = (ColorDrawable) colorDrawable.getConstantState().newDrawable()
                    .mutate();
            copy.setColor(
                    Color.argb(255, Color.red(color), Color.green(color), Color.blue(color)));
            return copy;
        }
    }
    return drawable;
}

enforceNonTranslucentBackground中的大致逻辑:当windowTranslucent == false,enforceNonTranslucentBackground会强制将背景更改为不透明背景(PS: 即使windowBackground 是 透明的 )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值