以编程方式显示键盘 Android

问题描述 投票:0回答:4

有没有办法在 Android O 版本以上的 Activity 中显示键盘?我有以下代码:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

它“仅”适用于以下 Android O 版本。

android android-softkeyboard
4个回答
7
投票

我有两个选择给你。首先,您可以使用RequestFocus

editText.requestFocus();

其次,您可以执行此代码来显示特定 EditText 的键盘

android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT);

补充一点,用这个来隐藏键盘:

android.view.View view = this.getCurrentFocus();   
android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

注意:这里的每个代码都经过测试并且可以工作。


1
投票

要显示键盘,

InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

如果你想聚焦到编辑文本,请使用

editText.requestFocus();

隐藏键盘,

InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);

0
投票

Kotlin 显示键盘的方法

现在 ToogleSoftInput 已被弃用。

 private fun showKeyboard() {
            val imm: InputMethodManager =
                 context?.getSystemService(Activity.INPUT_METHOD_SERVICE) as 
       InputMethodManager
         imm.showSoftInput(binding.yourEditText, 0)
        }

0
投票

对于 kotlin

extension
功能且可重用

fun View.hideKeyboard() {
    ViewCompat.getWindowInsetsController(this)?.hide(WindowInsetsCompat.Type.ime())
}

fun View.showKeyboard() {
    ViewCompat.getWindowInsetsController(this)?.show(WindowInsetsCompat.Type.ime())
}

fun View.showKeyboardAndFocus() {
    ViewCompat.getWindowInsetsController(this)?.show(WindowInsetsCompat.Type.ime())
    requestFocus()
}
© www.soinside.com 2019 - 2024. All rights reserved.