最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

kotlin - InputConnection Support on Android 9+ - Stack Overflow

programmeradmin3浏览0评论

I feel a little lost. I've created a subclass of TextureView which should support text input via keyboard. I've tested my code on physical device with Android 12 and Emulator and it works fine. But, it fails when using Android 9. I need support for this from Android 9+. Can someone hint me please, what could be the problem? Here's my code:

import "android.content.*"
import "android.text.InputType"
import "android.util.AttributeSet"
import "android.view.*"
import "android.view.inputmethod.*"
import "androidx.core.view.ViewCompat"

val myView = object : TextureView(context as Context) {
  private var inputConnection: BaseInputConnection? = null

  override fun onAttachedToWindow() {
      super.onAttachedToWindow()
      isFocusable = true
      isFocusableInTouchMode = true
      requestFocus()
      showKeyboard()

      ViewCompat.setOnReceiveContentListener(
          this,
          arrayOf(ClipDescription.MIMETYPE_TEXT_PLAIN)
      ) { _, content ->
          val text = content.clip.getItemAt(0).coerceToText(context as Context)
          if (text.isNotEmpty()) {
              (cbreceivecontent as Function1<Any, *>).invoke(text.toString())
          }
          null
      }
  }

  private fun showKeyboard() {
      ((context as Context).getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
          .showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
  }

  override fun onCreateInputConnection(outAttrs: EditorInfo?): InputConnection {
      outAttrs?.apply {
          inputType = InputType.TYPE_CLASS_TEXT
          imeOptions = EditorInfo.IME_ACTION_DONE
      }

      inputConnection = object : BaseInputConnection(this, true) {
          override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
              text?.let {
                  (cbcommittext as Function1<Any, *>).invoke(it.toString())
              }
              return supermitText(text, newCursorPosition)
          }
      }

      return inputConnection!!
  }

  override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
      event?.unicodeChar?.takeIf { it != 0 }?.let {
          (cbkeydown as Function1<Any, *>).invoke(it.toChar().toString())
          return true
      }

      return super.onKeyDown(keyCode, event)
  }
}
发布评论

评论列表(0)

  1. 暂无评论