如何在Kotlin中编写扩展函数?

问题描述 投票:-2回答:1

我只是想将我的正常函数转换为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)
                }
            }
        }
android android-studio kotlin kotlin-android-extensions
1个回答
4
投票

您甚至可以通过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)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.