我有Java代码,可以使用InputMethodManager隐藏软键盘。当我将代码转换为Kotlin时,相同的代码将引发NoMethodFound异常。
我可以轻松地在Java和Kotlin版本之间进行切换,并演示Java的正确行为和Kotlin的错误行为。
Java代码
searchText.clearFocus();
InputMethodManager imm = (InputMethodManager)dialog.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
try {
imm.hideSoftInputFromWindow(searchText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Throwable t) {
String stop = "here";
}
科特林码
searchText!!.clearFocus()
val imm = dialog!!.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
try {
imm.hideSoftInputFromWindow(searchText!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
} catch (t: Throwable) {
val stop = "here"
}
Java代码表现出正确的行为并关闭了软键盘。Kotlin代码引发异常
“ java.lang.NoSuchMethodError:没有虚拟方法hideSoftInputFromWindow(Landroid / os / IBinder; I)V类Landroid / view / inputmethod / InputMethodManager;或其超一流(出现“ android.view.inputmethod.InputMethodManager”的声明在/system/framework/framework.jar:classes2.dex)“
[此方法似乎在Context
中不可用。尝试从应用程序上下文中使用Context
。对于获取应用程序上下文,可以使用this之类的方法或在kotlin中进行一些有关获取应用程序的操作可能会有所帮助。
这不是答案,而是一种解决方法。我将Kotlin代码重构回Java,并将其作为静态方法放置在帮助程序类中。该方法从Kotlin调用。