Search code examples
androidkotlinandroid-softkeyboard

How to hide keyboard. System services not available to Activities before onCreate()


System services not available to Activities before onCreate()

I have dialog class MyPersonalDialog(mContext: Context) and this dialog contains EditText. I initiate class MyPersonalDialog by parsing context in there. val myPersonalDialog = MyPersonalDialog(this)

and then I chow dialog my calling myPersonalDialog.showMyDialog

this class:

class MyPersonalDialog(mContext: Context){

    fun showMyDialog(){
    val builder = AlertDialog.Builder(context)
    val layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    val view = layoutInflater.inflate(R.layout.dialog_edit_list_title, null)
    view.renameListTitle.requestFocus()
    val inputHelper = InputHelper(context)
    inputHelper.showDialogKeyboard()
    builder.setView(view)
    builder.setNegativeButton(R.string.cancel, { dialogInterface: DialogInterface, i: Int ->
        inputHelper.hideKeyboard(activity, view)
    })
    //some other code goes next
}

}

When user presses NegativeButton button hideKeyboard start to works

class InputHelper(val context: Context){
fun hideKeyboard(activity: Activity, view: View) {
        val inputManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
}

But this error appears: java.lang.IllegalStateException: System services not available to Activities before onCreate()

How can I fix this issue? I do not undestand why does this error appears because MyPersonalDialog class was initiated after onCreate

Solution is found:

class InputHelper(val context: Context){
fun showDialogKeyboard() {
    val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}

fun hideKeyboard(view: View) {
        val inputManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputManager.hideSoftInputFromWindow(view.getWindowToken(),0);
}}

Solution

  • try replacing fun hideKeyboard(activity: Activity, view: View) { val inputManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS) } } in InputHelper