BasePopupWindow.kt 2.39 KB
Newer Older
konghaorui committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
package com.yidianling.common.view.popupwindow

import android.app.Activity
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.Window
import android.widget.PopupWindow

/**
 * @author jiucheng
 * @描述:PopupWindow基类,后续PopupWindow可统一继承
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/8/9
 */
open class BasePopupWindow : View.OnTouchListener, PopupWindow.OnDismissListener {
    protected var popupWindow: PopupWindow? = null
    protected var mContext: Activity? = null
    protected var mView: View? = null
    protected var window: Window? = null

    constructor(mContext: Activity) {
        this.mContext = mContext
        popupWindow = PopupWindow(mContext)
        window = mContext.window
    }

    open fun initPopupwindow() {
        //设置点击空白处消失
        popupWindow!!.isTouchable = true
        popupWindow!!.setTouchInterceptor(this)
        popupWindow!!.isOutsideTouchable = true
        popupWindow!!.isFocusable = true
        popupWindow!!.setOnDismissListener(this)
    }


    override fun onDismiss() {
        val params = window!!.getAttributes()
        params.alpha = 1f
        window!!.setAttributes(params)
    }

    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        if (event != null) {
            if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                dismiss()
                return true
            }
        }
        return false
    }


    open fun dismiss() {
        if (popupWindow != null)
            popupWindow!!.dismiss()

        val params = window!!.attributes
        params.alpha = 1f
        window!!.attributes = params
    }


    open fun showAtLocation(parent: View, gravity: Int, x: Int, y: Int) {
        val params = window!!.attributes
        params.alpha = 0.5f
        window!!.attributes = params

        if (popupWindow != null) {
            popupWindow!!.showAtLocation(parent, gravity, x, y)
        }
    }

    open fun showAsDropDown(anchor: View, xoff: Int, yoff: Int) {
        val params = window!!.attributes
        params.alpha = 0.5f
        window!!.attributes = params
        if (popupWindow != null) {
            popupWindow!!.showAsDropDown(anchor, xoff, yoff)
        }
    }


    /**
     * 在底部显示
     */
    open fun showBottom(v: View) {
        showAtLocation(v, Gravity.BOTTOM, 0, 0)
    }
}