Kotlin 中显示和隐藏键盘

1、发生的原因:

1、我们希望在第一次进入页面的时候,不弹起软键盘;
2、当前页面手动点击弹起软键盘,离开当前页,去别的页面,关闭弹起软键盘;

解决:我们在Activity或者Fragment的基类中,直接写,调用即可。

2、首次进入页面,键盘不弹起,键盘弹起不挤压布局变形;

        <activity android:name=".ui.activity.login.LoginActivity"
            android:screenOrientation="portrait"
            android:configChanges="orientation|screenSize|locale"
            android:windowSoftInputMode="adjustNothing"
            />

3、Activity中控制键盘的显示和隐藏

abstract class BaseActivity<VM : BaseViewModel, VB : ViewBinding> : BaseVmVbActivity<VM, VB>() {
    private val imm: InputMethodManager? by lazy { getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager? }

    abstract override fun initView(savedInstanceState: Bundle?)



    override fun onPause() {
        super.onPause()
        //隐藏键盘
        hideSoftInput()
    }


    /**
     * 隐藏键盘
     */
    fun hideSoftInput() {
        this?.currentFocus?.let {
            imm?.hideSoftInputFromWindow(it.windowToken, 0)
        }
    }
    /**
     * 显示键盘
     */
    fun showSoftInput() {
        this?.currentFocus?.let {
            imm?.showSoftInput(it, 0)
        }
    }
}

4、Fragment中控制键盘的显示和隐藏

abstract class BaseFragment<VM : BaseViewModel, VB : ViewBinding> : BaseVmVbFragment<VM, VB>() {

    abstract override fun initView(savedInstanceState: Bundle?)

    /**
     * 懒加载 只有当前fragment视图显示时才会触发该方法
     */
    override fun lazyLoadData() {}

    override fun onPause() {
        super.onPause()
        //隐藏键盘
        hideSoftInput()
    }


    /**
     * 隐藏键盘
     */
    fun hideSoftInput() {
        val imm = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view?.windowToken, 0)
    }
    /**
     * 显示键盘
     */
    fun showSoftInput() {
        val imm = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容