实现DialogFragment全屏透明效果的方案

2020-10-12  本文已影响0人  baby_double

1、声明一个style

<style name="Dialog.FullScreen" parent="Theme.AppCompat.Dialog">
    <item name="android:padding">0dp</item>
    <item name="android:windowBackground">@android:color/transparent</item>
</style>

2、在DialogFragment中引用

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(STYLE_NO_FRAME, R.style.Dialog_FullScreen);
}

3、如果想将周边设置指定的透明值,可以在DialogFragment中的onStart设置

  @Override
public void onStart() {
    super.onStart();

    Window window = getDialog().getWindow();
    WindowManager.LayoutParams windowParams =window.getAttributes();
    windowParams.dimAmount = 0.7f; //将Window周边设置透明为0.7
    getDialog().setCanceledOnTouchOutside(false); //点击周边不隐藏对话框
    window.setAttributes(windowParams);

   //点击返回键不隐藏对话框
    getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                return true;
            }
            return false;
        }
    });
}
上一篇下一篇

猜你喜欢

热点阅读