当 EditText 获得焦点时自动显示软键盘的方法如何实现?

7
当我的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();

第四种方法是使用fork但并不理想。因此在这里写下了当EditText获得焦点时自动显示软键盘的解决方案。

之前,我使用了方法2并且它也起作用了。但现在不再起作用了。而且我创建了一个空项目,但是没有一个方法能够起作用。

更新:

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

可能是重复的问题:如何在EditText获得焦点时显示软键盘 - raukodraug
2个回答

8

您也可以为您的活动添加标志,这将自动显示键盘。

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

如果你希望在活动启动时应用焦点,这将非常有用。

此外,您还可以在片段中使用:

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);

@ip696,这是使用不同的标志,与您所拥有的不同。 - kandroidj
我尝试了所有的标志,但都没有起作用。但现在它终于成功了!我感到非常震惊!怎么做到的?谢谢! - ip696

1

在EditText的onFocusChange监听器中,使用WindowManager而不是InputMethodManager,因为它更可靠。

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);
    }
   } });

我不明白为什么不使用监听器的常规方式无法工作。 - ip696
@ip696 :可能是因为你使用了其他比EditText更早获取焦点的组件。所以这取决于你在布局中设计的层次结构。 - Jai
层次结构?你是指XML的顺序吗?这有关系吗? - ip696
我将布局从我的项目复制到测试项目中,键盘显示了。但在项目中却没有显示。 - ip696
我更新了添加主题的问题。你说的“依赖于你的活动”是什么意思? - ip696
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接