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

时间:2015-08-26 08:36:26

标签: 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字段后显示(即用我的手指)。有没有办法可以在不使用物理触摸的情况下自动显示电路板?

顺便说一句,我知道我如何指定宽度和高度并不是正确的做事方式。

3 个答案:

答案 0 :(得分:9)

感谢@ 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是当前活动的rootView。我没有对此进行测试,看看这是否适用于子视图。

答案 1 :(得分:4)

添加

    editText.requestFocus();

试试这个:

EditText editText = (EditText ) findViewById(R.id.myTextViewId);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager)   getSystemService(Context.INPUT_METHOD_SERVICE); 
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

确保edittext在触摸模式下可聚焦。你可以双向完成。

在xml中:

 android:focusableInTouchMode="true"
Java中的

editText.setFocusableInTouchMode(true);

答案 2 :(得分:0)

这将显示键盘

InputMethodManager imm = (InputMethodManager) 
        OrderMainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(txtCustomerId, InputMethodManager.SHOW_IMPLICIT);
如果您从听众调用键盘,请输入您的活动名称而不是此名称。按钮单击

相关问题