如何将对话框窗口背景设置为透明,而不影响其边距

Che*_*eng 12 android android-animation android-dialog

目前,我有以下对话框,我将对其项目执行展开/折叠动画.

在此输入图像描述

该对话框通过以下代码创建

import android.support.v7.app.AlertDialog;

final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
final AlertDialog dialog = builder.setView(view).create();
final ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

    public void onGlobalLayout() {
        ViewTreeObserver obs = view.getViewTreeObserver();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            obs.removeOnGlobalLayoutListener(this);
        } else {
            obs.removeGlobalOnLayoutListener(this);
        }

        // http://stackoverflow.com/questions/19326142/why-listview-expand-collapse-animation-appears-much-slower-in-dialogfragment-tha
        int width = dialog.getWindow().getDecorView().getWidth();
        int height = dialog.getWindow().getDecorView().getHeight();
        dialog.getWindow().setLayout(width, height);
    }
});
Run Code Online (Sandbox Code Playgroud)

但是,当执行动画时,这是副作用.

在此输入图像描述

请注意,动画后对话框中不需要的额外白色区域不是由我们的自定义视图引起的.它是对话框本身的系统窗口白色背景.

我倾向于使对话框的系统窗口背景变得透明.

final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
final AlertDialog dialog = builder.setView(view).create();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Run Code Online (Sandbox Code Playgroud)

虽然不再看到不需要的白色背景,但对话框的原始边距也消失了.(对话框宽度现在是全屏宽度)

在此输入图像描述

如何在不影响保证金的情况下使其透明?

Bar*_*ski 11

有一个非常简单的方法:

你需要"修改" Drawable用作背景的那个Dialog.这些种类的Dialogs使用InsetDrawable作为背景.

API> = 23

不幸的是,只有API> = 23的SDK允许您获取(方法)Drawable包装的源.有了这个,你可以做任何你想做的事情 - 例如将颜色改变为完全不同的东西(比如或某种东西).如果你使用这种方法,请记住包装是一个而不是一个!InsetDrawablegetDrawable()REDDrawableGradientDrawableColorDrawable

API <23

对于较低的API,您的("优雅")选项非常有限.

幸运的是,您不需要将颜色更改为某些疯狂的值,您只需将其更改为TRANSPARENT.为此,您可以使用setAlpha(...)方法InsetDrawable.

InsetDrawable background = 
            (InsetDrawable) dialog.getWindow().getDecorView().getBackground();
background.setAlpha(0);
Run Code Online (Sandbox Code Playgroud)

编辑(由于Cheok Yan Cheng的评论):

或者您实际上可以跳过转换InsetDrawable并获得相同的结果.请记住,这样做会导致在自身alpha上进行更改,InsetDrawable而不是在Drawable包装上进行更改InsetDrawable.


保留间距