我正在使用AlertDialog显示一个输入框。当我调用AlertDialog.show()时,对话框内部的EditText会自动聚焦,但软键盘不会自动显示。

我如何使软键盘自动显示时,对话框显示?(并且没有物理/硬件键盘)。类似于当我按下Search按钮调用全局搜索时,会自动显示软键盘。


当前回答

你可以在EditText上附加onFocusListener或在AlertDialog上附加onShowListener,并添加以下内容:

val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)

其他回答

我的方法使用了Android 11+的新方法,也支持旧版本:

fun Fragment.showKeyboard() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        ViewCompat.getWindowInsetsController(requireView())?.show(WindowInsetsCompat.Type.ime())
    } else {
        val focusedView = view?.findFocus() ?: view?.apply { requestFocus() }
        val imm = (context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
        val isShowSucceeded = imm.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT)
        if(!isShowSucceeded) {
            imm.toggleSoftInputFromWindow(
                view?.windowToken, 0, InputMethodManager.HIDE_IMPLICIT_ONLY)
    }
}

}

为什么这个答案-因为上面的解决方案将显示你的键盘,但它不会消失,如果你点击任何其他的编辑文本。因此,当EditText失去焦点时,您需要做一些事情使键消失。

你可以通过以下步骤来实现这一点:

Make the parent view(content view of your activity) clickable and focusable by adding the following attributes android:clickable="true" android:focusableInTouchMode="true" Implement a hideKeyboard() method public void hideKeyboard(View view) { InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),InputMethodManager.HIDE_IMPLICIT_ONLY ); } Lastly, set the onFocusChangeListener of your edittext. edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { hideKeyboard(v); } } });

你可以在EditText上附加onFocusListener或在AlertDialog上附加onShowListener,并添加以下内容:

val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)

我找到了这个例子http://android-codes-examples.blogspot.com/2011/11/show-or-hide-soft-keyboard-on-opening.html。在alert.show()之前添加以下代码。

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

尝试了很多,但这对我来说是有效的(kotlin):

        val dialog = builder.create()
        dialog.setOnShowListener {
            nameEditText.requestFocus()
            val s = ContextCompat.getSystemService(requireContext(), InputMethodManager::class.java)
            s?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
        }

        dialog.setOnDismissListener {
            val s = ContextCompat.getSystemService(requireContext(), InputMethodManager::class.java)
            s?.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
        }

        dialog.show()