在onCreate()之前, Activity 无法使用系统服务

我有对话框类MyPersonalDialog(mContext:Context),并且此对话框包含EditText。
我通过在其中解析上下文来初始化MyPersonalDialog类。
val myPersonalDialog = MyPersonalDialog(this)

然后我通过对话对话
myPersonalDialog.showMyDialog

这个类:

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
}

}

当用户按下NegativeButton按钮hideKeyboard开始工作
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)
}
}

但是出现此错误:
java.lang.IllegalStateException:在onCreate()之前,Activities无法使用系统服务

如何解决此问题?我不明白为什么会出现此错误,因为MyPersonalDialog类是在onCreate之后启动的

找到解决方案:
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);
}}

最佳答案

尝试更换
fun hideKeyboard(activity: Activity, view: View) { val inputManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS) } }中的InputHelper

09-26 09:04