Android开发经验谈Android开发Android开发

Android弹窗实现之Popupwindow及DialogFr

2018-09-03  本文已影响536人  木子饼干

popupwindow方式实现

使用PopupWindow,一般来说可以分为如下步骤:

     val layout = LayoutInflater.from(fragment.context).inflate(R.layout.dialog__plan, null)

实现PopupWindow对象实例

     popupWindow = PopupWindow(layout, ViewGroup.LayoutParams.WRAP_CONTENT,     ViewGroup.LayoutParams.WRAP_CONTENT, true)

设置PopupWindow背景、动画属性、控件实现及事件监听

    popupWindow.animationStyle = R.style.popp_anim
    backgroundAlpha(0.5f)
    layout.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
        popupWindow.dismiss()
    }
    layout.findViewById<TextView>(R.id.tv_sure).setOnClickListener {
        popupWindow.dismiss()
    }

在显示popwindow之前调用 backgroundAlpha(0.5f)将背景变暗,监听popupwindow状态,消失之后将背景回复

       popupWindow.setOnDismissListener {
        backgroundAlpha(1f)
    }

backgroundAlpha()方法实现具体代码

/**
 * 设置添加屏幕的背景透明度
 * @param bgAlpha
 */
fun backgroundAlpha(bgAlpha: Float) {
    val lp = this.window.attributes
    lp.alpha = bgAlpha
    this.window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
    this.window.attributes = lp
}

记得添加 this.window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND),否则部分机型可能无效,部分机型可以直接看到桌面

DidlogFragment方式实现

Android 官方推荐我们使用 DialogFragment 来代替 原有的Dialog ,因为DidlogFragment可复用性更高,更加简便。创建 DialogFragment一般来说有两种:

  1. 覆写其 onCreateView 方法
  2. 覆写其onCreateDialog方法

具体过程

方法一onCreateView

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
    //去掉默认样式中的title
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    val window = dialog.window
      //设置dialog背景透明
    window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

    // Inflate the layout for this fragment
    val view = inflater.inflate(R.layout.fragment_my_dialog, container, false)

    view.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
        dismiss()
    }
    view.findViewById<TextView>(R.id.tv_sure).setOnClickListener {
        dismiss()

    }
    return view
}

注意设置 window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)),否则可能使布局出现边等或者其他效果

方法二onCreateDialog

复写onCreateDialog方法,加载布局

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    // 设置主题的构造方法
    val dialog = Dialog(context!!, R.style.dl_dialog)
    val inflater = activity?.layoutInflater

    val view = inflater?.inflate(R.layout.fragment_dialog_dialog, null)
    view?.findViewById<TextView>(R.id.tv_cancel)?.setOnClickListener {
        dismiss()
    }

    view?.findViewById<TextView>(R.id.tv_sure)?.setOnClickListener {
        dismiss()
    }

    dialog.setContentView(view)
    return dialog
}

最后

给出MyDialogfragment

上一篇下一篇

猜你喜欢

热点阅读