繁花不似锦
由于PopupWindow只是增加了一个View到WindowManager你可以使用updateViewLayout (View view, ViewGroup.LayoutParams params)更新LayoutParams您的PopupWindow的contentView调用演出后..()。设置窗口标记FLAG_DIM_BEHIND将使窗口后面的所有内容变暗。使用dimAmount以控制暗淡的(1.0完全不透明到0.0为无暗淡)的量。请记住,如果您为背景设置背景,PopupWindow则会将其放入contentView容器中,这意味着您需要更新其父级。有背景:PopupWindow popup = new PopupWindow(contentView, width, height);popup.setBackgroundDrawable(background);popup.showAsDropDown(anchor);View container = (View) popup.getContentView().getParent();WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);WindowManager.LayoutParams p = (WindowManager.LayoutParams) container.getLayoutParams();// add flagp.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;p.dimAmount = 0.3f;wm.updateViewLayout(container, p);没有背景:PopupWindow popup = new PopupWindow(contentView, width, height);popup.setBackgroundDrawable(null);popup.showAsDropDown(anchor);WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);WindowManager.LayoutParams p = (WindowManager.LayoutParams) contentView.getLayoutParams();// add flagp.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;p.dimAmount = 0.3f;wm.updateViewLayout(contentView, p);棉花糖更新:在M上,PopupWindow将contentView包裹在一个名为mDecorView的FrameLayout中。如果您深入研究PopupWindow源,您会发现类似createDecorView(View contentView).mDecorView的主要目的是处理事件分发和内容转换,这是M的新增功能。这意味着我们需要再添加一个.getParent()来访问容器。背景需要更改为以下内容:View container = (View) popup.getContentView().getParent().getParent();API 18+的更好替代使用以下方法的解决方案ViewGroupOverlay:1)保留所需的根目录布局ViewGroup root = (ViewGroup) getWindow().getDecorView().getRootView();2)致电applyDim(root, 0.5f);或clearDim()public static void applyDim(@NonNull ViewGroup parent, float dimAmount){ Drawable dim = new ColorDrawable(Color.BLACK); dim.setBounds(0, 0, parent.getWidth(), parent.getHeight()); dim.setAlpha((int) (255 * dimAmount)); ViewGroupOverlay overlay = parent.getOverlay(); overlay.add(dim);}public static void clearDim(@NonNull ViewGroup parent) { ViewGroupOverlay overlay = parent.getOverlay(); overlay.clear();}