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

标签 android android-animation android-dialog

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

enter image description here

这个对话框是通过下面的代码创建的

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);
    }
});

但是,当执行动画时,会产生副作用。

enter image description here

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

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

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

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

enter image description here

如何在不影响边距的情况下使其透明?

最佳答案

有一个非常简单的方法可以做到这一点:

您需要“修改”用作Dialog 背景的Drawable。这些类型的Dialogs 使用InsetDrawable 作为背景。

API >= 23

只有 SDK API 23+ 允许您获取由 InsetDrawable(getDrawable() 方法)包装的源 Drawable。有了这个,你可以做任何你想做的事——例如将颜色更改为完全不同的颜色(例如 RED 或其他)。如果您使用这种方法,请记住包装的 DrawableGradientDrawable 而不是 ColorDrawable!

API < 23

对于较低的 API,您的(“优雅”)选项非常有限。

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

InsetDrawable background = 
            (InsetDrawable) dialog.getWindow().getDecorView().getBackground();
background.setAlpha(0);

编辑(作为 Cheok Yan Cheng's 评论的结果):

或者您实际上可以跳过转换为 InsetDrawable 并获得相同的结果。请记住,这样做会导致 InsetDrawable 本身的 alpha 发生变化,而不是 包裹的 Drawable 发生变化InsetDrawable.


retaining spacings

关于android - 如何将对话框窗口背景设置为透明,而不影响其边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36133121/

相关文章:

android - 将 AlertDialog 正按钮文本设置为粗体

android - Android中具有透明背景的对话框

java - 错误 : androidmanifest. xml 文件丢失 --> 我错过了什么?

android - 具有 scale 属性的 ObjectAnimator 使 bg 变黑?

android - 如何在我的 android 应用程序主屏幕中实现以下转换?

android - 添加带有淡入淡出动画的 ActionBar 项目

Android重新显示来自单独 fragment 的dialogfragment

java - LayoutInflater : No output is displayed, 中出现问题并且应用程序崩溃

android - Windows 10的React-Native Android问题

android - 如何创建具有配置 Activity 的应用小部件,并首次对其进行更新?