Android DialogFragment 实现

整理一下使用 DialogFragment
需要注意的是,Dialog弹出的左右边距是不能通过设置 root Layout 的 margin 来控制, 如果有需要,就再 Root Layout 里面再包裹一层,然后设置它的 margin 就可以了,

abstract class BaseDialogFragment : DialogFragment() {

    protected lateinit var binding: VB

    private var isCanceledOnTouchOutside: Boolean = true

    protected var gravity: Int = -1

    open fun isCancelable(cancelable: Boolean): BaseDialogFragment<*> {
        isCancelable = cancelable
        return this
    }

    open fun isCanceledOnTouchOutside(cancelableOnTouchOutside: Boolean): BaseDialogFragment<*> {
        isCanceledOnTouchOutside = cancelableOnTouchOutside
        return this
    }

    override fun onStart() {
        super.onStart()
        val dialog = dialog
        if (dialog != null) {
            val window = dialog.window
            val windowParams = window!!.attributes
            windowParams.dimAmount = 0.6f
            windowParams.flags = windowParams.flags or WindowManager.LayoutParams.FLAG_DIM_BEHIND
            windowParams.flags =
                windowParams.flags or WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
            window.attributes = windowParams
            dialog.setCancelable(isCancelable)
            dialog.setCanceledOnTouchOutside(isCanceledOnTouchOutside)
            window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            if (gravity != -1) {
                window.setGravity(gravity)
            }
        }
    }

    override fun show(manager: FragmentManager, tag: String?) {
        val t = javaClass.simpleName
        if (manager.findFragmentByTag(t) == null) {
            super.show(manager, t)
        }
    }


    fun show(manager: FragmentManager) {
        show(manager, "")
    }


    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

        val dialogBuilder = AlertDialog.Builder(requireActivity())
        val type = javaClass.genericSuperclass
        //        binding = DialogPrivacyBinding.inflate(LayoutInflater.from(context))
        if (type is ParameterizedType) {
            val clazz = type.actualTypeArguments[0] as Class
            val method = clazz.getMethod("inflate", LayoutInflater::class.java)
            binding = method.invoke(null, layoutInflater) as VB
            dialogBuilder.setView(binding.root)
        }
        initData()
        return dialogBuilder.create()
    }

    abstract fun initData()
}

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