You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并两个Activity扩展函数简化SearchView软键盘隐藏逻辑?

简化SearchView触摸隐藏软键盘的扩展函数

我已经实现了触摸屏幕时隐藏SearchView软键盘的功能,但现在想把现有的两个扩展函数合并成一个,听说用lambda或者类似语法可以做到,但不太熟悉相关写法,求帮忙优化!

现有实现代码

调用代码(Activity中,sv为SearchView实例)

hideKeyboard(this, sv)

现有扩展函数

fun Activity.hideKeyboard(context: Context, sv: SearchView) { 
    hideKeyboard(HideKeyboardWithSearchView(context, sv)) 
} 
fun Activity.hideKeyboard(hideKeyboard: HideKeyboardWithSearchView) { 
    window.decorView.rootView.setOnTouchListener { _, _ -> 
        hideKeyboard.start() 
        return@setOnTouchListener false 
    } 
}

功能实现类

import android.content.Context 
import android.support.v7.widget.SearchView 
import android.view.inputmethod.InputMethodManager 

class HideKeyboardWithSearchView(private val context: Context, private val sv: SearchView) { 
    fun start() { 
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager 
        imm.hideSoftInputFromWindow(sv.windowToken, 0) 
        sv.clearFocus() 
    } 
}

优化解决方案

结合rya和Pawel的思路,我们可以直接把两个扩展函数合并成一个,去掉多余的中间层,直接在扩展函数里完成触摸监听的设置和隐藏逻辑的调用:

fun Activity.hideKeyboard(sv: SearchView) {
    window.decorView.rootView.setOnTouchListener { _, _ ->
        HideKeyboardWithSearchView(this, sv).start()
        return@setOnTouchListener false
    }
}

这样调用的时候只需要在Activity里写 hideKeyboard(sv) 就可以了,既简化了扩展函数的结构,也让调用更简洁。


内容的提问来源于stack exchange,提问作者Gabi Moreno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:56:44