Android DialogFragment弹框实现

前言:

网上说了一堆好处,我只说自己深有体会的两点吧
1.屏幕横竖屏切换的时候,弹框可以保存状态
2.可以在popwindow中使用

使用步骤

1.创建继承DialogFragment的dialogFragment类

public class CardDialogFragment extends DialogFragment {
    public static CardDialogFragment newInstance() {
        Bundle args = new Bundle();
        CardDialogFragment fragment = new CardDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.gravity = Gravity.CENTER;
        window.setAttributes(params);
        window.setBackgroundDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.circle5_white));
        window.setWindowAnimations(R.style.BottomDialog_Animation);
        //设置边距
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        getDialog().getWindow().setLayout((int) (dm.widthPixels * 0.72), ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_live_user_card, container, false);
       ....
        return view;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return super.onCreateDialog(savedInstanceState);
    }
}
说明:

onStart()中的方法是设置弹框的位置和背景的,详细看注释。
注意:设置背景后,xml中的背景设置以及边距才会生效。所以一般在onStart中设置背景为透明色
onCreateView()自定义的dialog实现,适用于复杂的界面。
onCreateDialog()利用AlertDialog实现,适用于简单的界面。
2.显示

 LiveUserCardDialogFragment fragment = LiveUserCardDialogFragment.newInstance();
                fragment.show(getFragmentManager(),"");

3.监听DialogFragemnt的onDismisslistener方法

  • 当前Activity继承DialogInterface.OnDismissListener
  • 重写DialogFragment中的onDismiss方法
    eg:
 @Override
    public void onDismiss(final DialogInterface dialog) {
        super.onDismiss(dialog);
        final Activity activity = getActivity();
        if (activity instanceof DialogInterface.OnDismissListener) {
            ((DialogInterface.OnDismissListener) activity).onDismiss(dialog);
        }
    }

资料
Android 自定义 DialogFragment 宽度问题
~~喵印

你可能感兴趣的:(Android DialogFragment弹框实现)