我想在EditText被聚焦时自动显示软键盘(如果设备没有物理键盘),我有两个问题:

当我的活动显示时,我的EditText是集中的,但键盘不显示,我需要再次单击它来显示键盘(它应该显示时,我的活动显示)。 当我在键盘上点击完成时,键盘被解散,但EditText保持集中,我不想(因为我的编辑已经完成)。

继续说,我的问题是有一些更像iPhone的东西:保持键盘与我的EditText状态同步(聚焦/不聚焦),当然,如果有物理键盘,也不会呈现软键盘。


当前回答

我把这里的所有东西结合起来,对我来说是有效的:

public static void showKeyboardWithFocus(View v, Activity a) {
    try {
        v.requestFocus();
        InputMethodManager imm = (InputMethodManager) a.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
        a.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

其他回答

我最近在一些简单的代码案例中有一些运气 在下面。我还没有完成所有的测试,但是....

EditText input = (EditText) findViewById(R.id.Input);
input.requestFocus();    
input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0f, 0f, 0));
input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0f, 0f, 0));

键盘很快就出现了。

以下是我从Square得到的一个更可靠的解决方案:

fun View.focusAndShowKeyboard() { /** * This is to be called when the window already has focus. */ fun View.showTheKeyboardNow() { if (isFocused) { post { // We still post the call, just in case we are being notified of the windows focus // but InputMethodManager didn't get properly setup yet. val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT) } } } requestFocus() if (hasWindowFocus()) { // No need to wait for the window to get focus. showTheKeyboardNow() } else { // We need to wait until the window gets focus. viewTreeObserver.addOnWindowFocusChangeListener( object : ViewTreeObserver.OnWindowFocusChangeListener { override fun onWindowFocusChanged(hasFocus: Boolean) { // This notification will arrive just before the InputMethodManager gets set up. if (hasFocus) { this@focusAndShowKeyboard.showTheKeyboardNow() // It’s very important to remove this listener once we are done. viewTreeObserver.removeOnWindowFocusChangeListener(this) } } }) } }

代码从这里开始。

这对我很管用。你也可以尝试用这个来显示键盘:

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

在onCrete() activity()方法的editText上调用requestFocus()方法,并在相同的editText上调用clearFocus()方法,当在键盘上单击完成。

这很疯狂,但确实有效

fun showKeyboard(view: View) {
    try {
        InputMethodManager::class.java.getMethod(
                "showSoftInputUnchecked",
                Int::class.javaPrimitiveType,
                ResultReceiver::class.java
        ).apply {
            isAccessible = true
            invoke(view.context.inputMethodManager, 0, null)
        }
    }
    catch (e: Exception) {
       e.printStackTrace()
    }
}