相似微信根据手指长按位置精准弹出的PopupWindow

MotionEventPopupWindow

相似微信根据手指长按位置精准弹出的PopupWindow,自动根据左右上下边距调整显示的方向。git

APK体验包github

项目地址bash

准备工做

一、导入依赖微信

implementation 'com.kcrason:motionevent-popupwindow:1.0.0'
复制代码

简单使用(纯微信效果)

一、在须要显示的Activity重写dispatchTouchEvent,并设置一个变量用于保存motionEvent。(若是须要设置一个全局的MotionEvent,则须要在BaseActivity重写dispatchTouchEvent并提供一个方法获取motionEvent对象便可)app

override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        this.mMotionEvent = ev
        return super.dispatchTouchEvent(ev)
    }
复制代码

二、给须要触发显示popupwindow的view设置单击或长按时显示popupwindow,显示popupwindow时,将motionEvent变量传递进去。ide

txtCenterClick.setOnLongClickListener {
            CommonMotionEventPopupWindow(this)
                .showOptions(arrayListOf("复制", "粘贴", "发送", "翻译", "发送给好友"))
                .setOnClickItemOptionsListener { position, optionName ->
                    Toast.makeText(this, "this is $position , optionName:$optionName", Toast.LENGTH_SHORT).show()
                }
                .showMotionEventPopupWindow(it, mMotionEvent)
            return@setOnLongClickListener true
        }
复制代码

自定义界面的Popupwindow

一、建立新类继承BaseMotionEventPopupWindow便可。ui

class CustomMotionEventPopupWindow(context: Context) :BaseMotionEventPopupWindow(context) {
    override fun init() {
        //初始化一些参数
    }

    override fun getContainerLayoutId(): Int {
        //返回你须要显示的popupwindow xml
    }

    override fun getRealPopupWindowHeight(): Int {
        //返回popupwindow真实的高度,该高度在计算显示popupwindow的位置时须要用到,必须保证其准确性。
    }

    override fun getWindowWidth(): Int {
        //返回popupwindow的宽度,通常使用固定的值便可。
    }
}
复制代码

二、在须要显示的地方调用showMotionEventPopupWindow(anchor: View?, currentMotionEvent: MotionEvent?)方法显示popupwindowthis

效果展现

结语

实现比较简单,就不作过多介绍了,有兴趣能够download代码查看。spa

相关文章
相关标签/搜索