Android 开发过程中,自定义dialog 用得很多,通常都是通过继承Dialog, 再加载自定义的xml来实现。
1 | //自定义Dialog |
运行后,发现效果如下,
我们发现,match_parent属性根本没有生效。查看Dialog源码才发现,默认Dialog是有一个theme属性的,坑。
Dialog部分代码如下,
1 | /** |
其中
if (themeResId == 0) {
final TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.dialogTheme, outValue, true);
themeResId = outValue.resourceId;
}
从上述代码可以看出,若Dialog没有设置默认样式,系统会自动给你适配为R.attr.dialogTheme样式。
而查看themes.xml后,发现 dialogTheme样式是自带有Padding值的,所以match_parent自然是无效的。
那么,如何实现match_parent呢
(1) 设置padding值为0。
1 | dialog.getWindow().getDecorView().setPadding(0, 0, 0, 0); |
(2) 自定义一个Theme,覆盖原生Theme。
1 | OrderFilterDialog dialog = new OrderFilterDialog(context, R.style.test); |
运行效果如下,