键盘仅在第二次尝试后显示

时间:2013-08-23 11:42:19

标签: android android-edittext android-input-method

在我的应用中,在某些事件后,我希望我的用户填写EditText。为此,我请求关注此EditText并尝试使用此代码显示键盘:

public void onGivenEvent(int which) {
  mMyDialog.dismiss(getActivity());
  mMyEditField.requestFocus();
  InputMethodManager imm =
      (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
  imm.showSoftInput(mMyEditField, InputMethodManager.SHOW_IMPLICIT);
}

mMyEditField的xml如下所示:

<EditText
  android:id="@+id/edit_field"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_gravity="center"
  android:layout_marginLeft="10dp"
  android:background="@null"
  android:digits="0123456789.,"
  android:freezesText="true"
  android:hint="some hint"
  android:imeOptions="actionDone"
  android:inputType="numberDecimal"
  android:maxLength="15"
  android:selectAllOnFocus="true"
  android:singleLine="true"
  android:textColor="@android:color/black"
  android:textSize="16sp" />

有趣的是,此代码在首次尝试时不显示键盘。执行此代码一次后,设备旋转键盘正确显示。我有android:selectAllOnFocus="true"无法正常工作的类似问题,但我使用了解决方法 - 我将OnFocusChangeListener设置为mMyEditField.selectAll()

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

从onGivenEvent()函数调用此方法

public void showSoftKeyboard() {
        try {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.SHOW_FORCED, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
相关问题