如何在 EditText 获得焦点时自动显示软键盘

How Show soft keyboard automatically when EditText receives focus

我想在我的 EditText 获得焦点时显示键盘。我尝试了很多方法,但没有任何帮助。 我试过: 1.

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);

有不同的标志。

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

  1. <requestFocus />

4.

 editText.setOnFocusChangeListener(new OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    editText.post(new Runnable() {
                        @Override
                        public void run() {
                            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
                        }
                    });
                }
            });
            editText.requestFocus();

4 方法是分叉的,但它不是很好的解决方案。所以这里写成Show soft keyboard automatically when EditText receives focus

之前我用的是方法二,很管用。但现在不再了。我创建了一个空白项目,但它不起作用,none 方法

更新:

<style name="Theme.TransparencyDemo" parent="android:Theme.Light.NoTitleBar">
        <item name="android:windowTranslucentStatus">true</item>
        <item name="android:windowTranslucentNavigation">true</item>
    </style>

在 edittext 的 onFocusChange 侦听器中使用 WindowManager 而不是 InputMehtodManager,因为它可靠。

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
    if (hasFocus) {
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
   } });

您也可以向 activity 添加标志,这将自动显示键盘

<activity name="package.ActivityName" android:windowSoftInputMode="stateVisible"/>

如果您希望在 activity 启动时应用焦点,这将非常有用

你也可以在Fragment中使用:

InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

或在Activity

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