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

Fen*_*tel 1 android kotlin android-studio kotlin-android-extensions

我只想将我的普通函数转换为 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)
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

hot*_*key 7

您甚至可以使用 IDE 提供的自动重构来完成此操作:将光标放在要转换为接收器的参数上,按Alt+Enter并选择Convertparameter toreceiver

结果是:

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)