在 Resume 上显示软键盘

show soft keyboard onResume

找不到明确的答案,基本上我有一个带有 EditText 字段的 activity。软键盘在清单中设置为可见,因此当 activity 启动时键盘可见,但是如果用户导航离开并 returns 使用后退按钮,键盘将隐藏(我需要它在恢复时可见)。 我已将以下方法添加到我的 onResume 但似乎不起作用? 知道我在这里遗漏了什么吗?

private void showSoftKeyboard(){
    quickListName.requestFocus();
    InputMethodManager imm = D(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(quickListName,InputMethodManager.SHOW_IMPLICIT);
}

当您收到 onStop 回调时,尝试在 EditText 上调用 clearFocus

试试这个:

imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

以前,我在 onResume() 方法中使用了下面的代码,如果为此 activity 调用了 onPause() 方法,软键盘就会出现,然后我回到这个 activity.但是有一种情况会调用此 activity 的 onStop() 方法。当我再次返回此 activity 时,onResume() 被调用但未显示软键盘。

InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(this.getCurrentFocus(), InputMethodManager.SHOW_IMPLICIT);

我在 onResume() 方法中使用了以下代码而不是上面提到的代码,以便在还调用此 activity 的 onStop() 时显示软键。

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

尝试{ InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } 赶上(异常 e){ e.printStackTrace(); }

试试这个:

override fun onResume() {
    super.onResume()
    val imm = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
}

override fun onPause() {
    super.onPause()
    val imm = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
}

这会强制键盘在 onResume() 方法中打开并在 onPause() 方法中关闭。

您应该尝试从片段的 onResume 显示键盘。使用 InputMethodManager.toggleSoftInput 是一种 hack,不适用于 Android 11 (R),并且您不会立即知道键盘是否会显示。

为什么键盘没有显示?

当 window 中的 activity 刚刚启动时(包括从后台运行的 return),window 不会立即被标记为已聚焦.当您在 onResume 中调用 InputMethodManager.showSoftInput 时,它将 return 为假,因为尽管您试图从中显示键盘的视图可能已聚焦,但它仍在 window 中那不是。这样键盘就不会出现了。

正确的做法是什么?

正确的方法是覆盖 Activity.onWindowFocusChanged 并将其传递给您的片段,或者直接从那里显示键盘。这是后者的片段:

@Override
public void onWindowFocusChanged(boolean isFocused) {
  if (!isFocused) {
    return;
  }
  InputMethodManager inputMethodManager = 
      (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
  inputMethodManager.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
}