相似微信根據手指長按位置精準彈出的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
}
複製代碼
一、建立新類繼承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