gpt4 book ai didi

android - 如何隐藏键盘。系统服务在 onCreate() 之前对 Activity 不可用

转载 作者:行者123 更新时间:2023-11-29 00:53:50 25 4
gpt4 key购买 nike

在 onCreate() 之前系统服务对 Activity 不可用

我有对话框类 MyPersonalDialog(mContext: Context) 并且此对话框包含 EditText。我通过在其中解析上下文来启动 MyPersonalDialog 类。val myPersonalDialog = MyPersonalDialog(这个)

然后我chow dialog my calling我的个人对话.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 按钮时,隐藏键盘开始工作

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() 之前对 Activity 不可用

我该如何解决这个问题?我不明白为什么会出现这个错误,因为 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) } 输入助手

关于android - 如何隐藏键盘。系统服务在 onCreate() 之前对 Activity 不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56818411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com