android 自定义键盘长按弹窗

时间:2024-01-25 15:56:56
自己记忆,下次不用找
KeyboardView的onLongPress是长按监听,通过onLongPress可以获取键盘上用户长按的字母

override fun onLongPress(popupKey: Keyboard.Key): Boolean {
    val label = popupKey.label
    if (!TextUtils.isEmpty(label) && popupKey.codes.get(0) != MyKeyCode.CODE_SPACE && popupKey.codes.get(0) != MyKeyCode.KEYCODE_DONE) {
        val str = label.toString()
         
            keyboardPopup = KeyboardPopup(context, popupKey)
            val drawable = context.resources.getDrawable(R.drawable.bg_white_12)
            keyboardPopup?.setBackgroundDrawable(drawable)
            keyboardPopup?.update()
            keyboardPopup?.showAtLocation(this, Gravity.NO_GRAVITY, popupKey.x, popupKey.y)

            invalidateAllKeys()
        
        return true
    }
    return super.onLongPress(popupKey)
}

配合onTouchEvent可以做到弹出弹窗后,选择弹窗内容

override fun onTouchEvent(event: MotionEvent): Boolean {
    when (event.action) {
        MotionEvent.ACTION_MOVE -> {
            val x = event.x.toInt()
            val y = event.y.toInt()
            keyboardPopup?.run {
                if (this.isShowing()) {
                    this.handleTouch(x, y)
                }
            }
            return false
        }
        MotionEvent.ACTION_UP -> {
            keyboardPopup?.run {
                if (this.isShowing()) {
                    val inputMethodService = context as? MyInputMethodService
                    val ic = inputMethodService?.currentInputConnection
                    ic?.commitText(this.selectedLetter, 1)
                    this.dismiss()
                    keyboardPopup = null
                }
            }
        }
    }
    return super.onTouchEvent(event)

}

keyLetters就是你的弹窗展示的候选字的集合,letterTextView就是弹窗内展示选中字的控件

fun handleTouch(x: Int, y: Int) {
    if (keyLetters?.size == 0) {
        return
    }
    if (contentView.width == 0) {
        return
    }


    // 根据手指滑动的位置计算选中的字母
    val letterIndex = (x / (contentView.width / keyLetters!!.size)).coerceIn(0, keyLetters!!.size - 1)

    val letterTextView = contentView.findViewById<TextView>(R.id.letterTextView)
}