Android : How to prevent softkeyboard hidden when hardwarekeyboard input

245 Views Asked by At

I created EditText and applied it to the showSoftInput of InputMethodManager. When I enter a physical key, the keyboard is automatically hidden.

I want to prevent the keyboard from automatically being hidden.

I've tried the method below. 1. use showSoftInput Flag ImputMethodManager.SHOW_IMPLICIT, SHOW_FORCED 2. use InputConnectionWrapper in EditText, The string and the number work normally. but ctrl, Tab, Alt, F1,F2. Entering a key hides the keyboard.

I expect the keyboard to not be hidden when I enter the physical key. Thank you for reading.

1

There are 1 best solutions below

2
alireza easazade On BEST ANSWER

a good option is just to close the softkeyboard when there is an input from hardware keyboard

Android classes usually provide event handlers, you can implement when subclassing them. The Activity class has the following event handlers:

  • onKeyDown(int keyCode, KeyEvent event)
  • onKeyLongPress(int keyCode, KeyEvent event)
  • onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
  • onKeyShortcut(int keyCode, KeyEvent event)
  • onKeyUp(int keyCode, KeyEvent event)

In addition all views have the following event handlers:

  • onKeyDown(int, KeyEvent)
  • onKeyUp(int, KeyEvent)

I guess there are many other classes that have similar event handlers for key events, but this should be enough for your situation. The KeyEvent then contains information about the pressed key, i.e. the key code.

in you case you might want to do something like this :

in you activity or view class override on of onKeyDown or onKeyUp methods and hide the softkeyboard in there like:

override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        hideSoftKeyboard()
        return super.onKeyUp(keyCode, event)
}

or you can add a keyListener for your edittext

mEditText.setOnKeyListener { v, keyCode, event ->
       hideSoftKeyboard()
       return@setOnKeyListener when (keyCode) {
           KeyEvent.ACTION_UP -> {
               hideSoftKeyboard()
               true
           }
           else -> false
       }
}

how to close softKeyword:

fun hideSoftKeyboard() {
   try {
        val inputMethodManager = getSystemService(
            Activity.INPUT_METHOD_SERVICE
        ) as InputMethodManager
        inputMethodManager.hideSoftInputFromWindow(
            currentFocus!!.windowToken, 0)
    } catch (e: Exception) {}
}