当前,我有以下对话框,我将对其项目执行扩展/折叠动画。
该对话框是通过以下代码创建的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);
}
});
但是,在执行动画时,这是副作用。
请注意,动画后对话框中多余的多余白色区域不是由我们的自定义 View 引起的。它是对话框本身的系统窗口白色背景。
我倾向于使对话框的系统窗口背景变得透明。
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
final AlertDialog dialog = builder.setView(view).create();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
尽管不再看到不需要的白色背景,但对话框的原始边距也消失了。 (对话框的宽度现在是全屏宽度)
如何在不影响利润的情况下使其透明?
最佳答案
有一个很简单的方法可以做到这一点:
您需要“修改”用作Drawable背景的Dialog。这些Dialogs使用InsetDrawable作为背景。
API> = 23
只有SDK API 23+允许您获取由Drawable包装的源InsetDrawable(getDrawable()方法)。有了这个,您可以做任何您想做的事-例如将颜色更改为完全不同的颜色(例如RED或其他颜色)。如果使用这种方法,请记住,包装的Drawable是GradientDrawable而不是ColorDrawable!
API <23
对于较低的API,您的(“优雅”)选项非常有限。
幸运的是,您无需将颜色更改为一些疯狂的值,只需将其更改为TRANSPARENT即可。为此,您可以在setAlpha(...)上使用InsetDrawable方法。InsetDrawable background =
(InsetDrawable) dialog.getWindow().getDecorView().getBackground();
background.setAlpha(0);
编辑(作为Cheok Yan Cheng's注释的结果):
或者您实际上可以跳过转换为InsetDrawable并获得相同的结果。请记住,这样做会导致alpha在InsetDrawable本身而不是Drawable包裹的InsetDrawable上更改。