Android:强制键盘出现并专注于 EditText

标签 android android-layout

在此先感谢您的帮助。

我希望键盘出现在以下代码的末尾或执行期间。

    // edit text
    EditText editText = new EditText(activity);
    editText.setBackgroundColor(Color.WHITE);
    editText.setGravity(Gravity.TOP);
    editText.setText("Type here...");

    RelativeLayout relativeLayoutEditText = new RelativeLayout(activity);
    RelativeLayout.LayoutParams paramRelativeLayoutEditText = new RelativeLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, 43 * display.getHeight() / 80 );
    paramRelativeLayoutEditText.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    relativeLayoutEditText.addView(editText,paramRelativeLayoutEditText);

    // add all created views to rootView
    rootView.addView(relativeLayoutEditText, paramEditText);

    // open keyboard
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

但键盘仅在触摸 editText 字段后出现(即用我的手指)。有没有一种方法可以让看板自动出现而无需使用物理触摸?

顺便说一句,我知道我指定宽度和高度的方式并不完全正确。

最佳答案

多亏了@Shubham 的链接,我才能够弄明白。但是,解决方案不是链接中给出的答案。这是第二个答案。

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

编辑:

一旦使用上述解决方案,键盘将保留在屏幕上,直到用户按下后退按钮或主页按钮(有时需要几次)。要卸下键盘,请使用此

imm.toggleSoftInputFromWindow(rootView.getWindowToken(), 0,0);

在我的例子中,rootView 是当前 Activity 的 rootView。我还没有测试过它是否适用于 subview 。

关于Android:强制键盘出现并专注于 EditText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32221724/

相关文章:

java - 如何将按钮添加到 Android 中的推送通知

android - 使用 inflater 包含 edittext 时按钮不会下降

android - 从API 24以上版本的应用程序打开APK文件

android - 选择大于 3mb 的照片时,cordova 应用程序崩溃

android - android如何处理字体文件?

android - CoordinatorLayout 中的 ViewPager 意外收缩

android微调器下拉列表

android - MapActivity 从 OnClickListener 启动

android - 如何实现一个android :background that doesn't stretch?

Android - 如何动态更改 fragment 布局