我可以使用PopupWindow而不是Dialog来调暗背景吗?我问这个是因为我使用的是Dialogs,但Dialog并没有显示在点击的项目下方,而PopupWindow我已经在项目下面显示了弹出窗口。
答案 0 :(得分:20)
我使用以下代码,对我来说效果很好。
public static void dimBehind(PopupWindow popupWindow) {
View container;
if (popupWindow.getBackground() == null) {
if (VERSION.SDK_INT >= VERSION_CODES.M){
container = (View) popupWindow.getContentView().getParent();
} else {
container = popupWindow.getContentView();
}
} else {
if (VERSION.SDK_INT >= VERSION_CODES.M) {
container = (View) popupWindow.getContentView().getParent().getParent();
} else {
container = (View) popupWindow.getContentView().getParent();
}
}
Context context = popupWindow.getContentView().getContext();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams p = (WindowManager.LayoutParams) container.getLayoutParams();
p.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
p.dimAmount = 0.3f;
wm.updateViewLayout(container, p);
}
来自This answer。
更新
下面的fdermishin的答案更好。我已经向后测试了API级别19,它运行良好。
如果您使用kotlin,最好将其用作kotlin扩展名:
//Just new a kotlin file(e.g. ComponmentExts),
//copy the following function declaration into it
/**
* Dim the background when PopupWindow shows
*/
fun PopupWindow.dimBehind() {
val container = contentView.rootView
val context = contentView.context
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val p = container.layoutParams as WindowManager.LayoutParams
p.flags = p.flags or WindowManager.LayoutParams.FLAG_DIM_BEHIND
p.dimAmount = 0.3f
wm.updateViewLayout(container, p)
}
//then use it in other place like this:
popupWindow.dimBehind()
答案 1 :(得分:13)
似乎我想出了如何摆脱API版本检查。使用container = popupWindow.getContentView().getRootView()
解决了这个问题,但是我还没有对旧API进行过测试。适应Junyue Cao的解决方案:
public static void dimBehind(PopupWindow popupWindow) {
View container = popupWindow.getContentView().getRootView();
Context context = popupWindow.getContentView().getContext();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams p = (WindowManager.LayoutParams) container.getLayoutParams();
p.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
p.dimAmount = 0.3f;
wm.updateViewLayout(container, p);
}
答案 2 :(得分:4)
JiaJiaGu的解决方案有效,但popupWindow会与导航栏重叠,因为它会清除所有其他标志。
所以我在这里稍作改动:
use Mautic\Auth\ApiAuth;
use Mautic\Auth\OAuth;
我发布了一个新答案,因为我无法评论佳佳谷的答案。