我只是想将我的正常函数转换为Kotlin中的扩展函数。
这是我的功能,
fun hideKeyboard(activity: Activity) {
if (activity != null) {
activity.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_SATE_HIDDEN)
val view: View = activity.currentFocus
if (true) run {
val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
}
您甚至可以通过IDE提供的自动重构来执行此操作:将光标放在要转换为接收器的参数上,按Alt + Enter并选择将参数转换为接收器。
结果是:
fun Activity.hideKeyboard() {
if (this != null) { // Note: this check is redundant, since the type is not-null
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_SATE_HIDDEN)
val view: View = currentFocus
if (true) run {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
}