猿问

激活Android PopupWindow时背景模糊或暗淡

当我使用来显示弹出窗口时,我希望能够使背景模糊或变暗popup.showAtLocation,并在popup.dismiss调用时取消模糊/暗淡背景。

我曾尝试应用布局PARAMS FLAG_BLUR_BEHINDFLAG_DIM_BEHIND我的活动,但是这似乎只是模糊和朦胧的背景,一旦我的应用程序已启动。

我如何仅使用弹出窗口进行模糊/变暗?


qq_花开花谢_0
浏览 1234回答 3
3回答

繁花不似锦

由于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();}

富国沪深

在您的xml文件中,添加宽度和高度为“ match_parent”的类似内容。<RelativeLayout&nbsp; &nbsp; &nbsp; &nbsp; android:id="@+id/bac_dim_layout"&nbsp; &nbsp; &nbsp; &nbsp; android:layout_width="match_parent"&nbsp; &nbsp; &nbsp; &nbsp; android:layout_height="match_parent"&nbsp; &nbsp; &nbsp; &nbsp; android:background="#C0000000"&nbsp; &nbsp; &nbsp; &nbsp; android:visibility="gone" ></RelativeLayout>在您的活动中//setting background dim when showing popupback_dim_layout = (RelativeLayout) findViewById(R.id.share_bac_dim_layout);最后,在显示popupwindow时使其可见,并在退出popupwindow时使其不可见。back_dim_layout.setVisibility(View.VISIBLE);back_dim_layout.setVisibility(View.GONE);
随时随地看视频慕课网APP

相关分类

Android
我要回答