在ActionBar上显示SearchView的软键盘

Jon*_*ryl 11 android actionbarsherlock

我们在ActionBar上有一个SearchView,它被设置为非图标化.由于我们在视图中没有任何内容直到用户输入要搜索的内容,因此将SearchView初始焦点放在一边是有意义的,并确保软键盘显示为用户输入文本做好准备 - 否则他们'我总是必须先在SearchView中点击.

我可以通过调用来给予SearchView焦点

searchView.requestFocus();
Run Code Online (Sandbox Code Playgroud)

但我不能让软键盘出现.在我们的另一个片段中,我有一个我们想要聚焦的EditText我可以通过调用让软键盘出现在那里

InputMethodManager mgr = (InputMethodManager)getActivity().getSystemService(
            Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
Run Code Online (Sandbox Code Playgroud)

但这只是在SearchView上不起作用.必须有可能让它发挥作用.

Jon*_*ryl 22

在StackOverflow周围进一步搜索,我发现了这个问题:

强制打开软键盘

其中包含一个适合我的解决方案:

((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).
    toggleSoftInput(InputMethodManager.SHOW_FORCED,
                    InputMethodManager.HIDE_IMPLICIT_ONLY);
Run Code Online (Sandbox Code Playgroud)


Ulr*_*ler 8

我有一个类似的问题,这里提出的解决方案都没有奏效。有些根本没有让键盘出现,有些则显示键盘,但那里的按键不起作用。

唯一有效的是:

                    // hack for making the keyboard appear
                    searchView.setIconified(true);
                    searchView.setIconified(false);
Run Code Online (Sandbox Code Playgroud)


Jam*_*mie 6

我正在使用带有setIconifiedByDefault(false)的SearchView.使用Android 4.4.2进行测试,我能够让键盘实际显示的唯一方法是查看SearchView的源代码并模仿它如何请求键盘显示.我已经尝试过我能找到/想到的所有其他方法,这是我能让键盘可靠显示的唯一方法.不幸的是,我的方法需要一些反思.

在onCreateOptionsMenu(菜单)中:

searchView.requestFocus();
searchView.post(new Runnable() {
    @Override
    public void run() {
        showSoftInputUnchecked();
    }
});
Run Code Online (Sandbox Code Playgroud)

然后创建一个方法来在InputMethodManager中调用隐藏方法"showSoftInputUnchecked":

private void showSoftInputUnchecked() {
    InputMethodManager imm = (InputMethodManager)
            getSystemService(Context.INPUT_METHOD_SERVICE);

    if (imm != null) {
        Method showSoftInputUnchecked = null;
        try {
            showSoftInputUnchecked = imm.getClass()
                    .getMethod("showSoftInputUnchecked", int.class, ResultReceiver.class);
        } catch (NoSuchMethodException e) {
            // Log something
        }

        if (showSoftInputUnchecked != null) {
            try {
                showSoftInputUnchecked.invoke(imm, 0, null);
            } catch (IllegalAccessException e) {
                // Log something
            } catch (InvocationTargetException e) {
                // Log something
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

与访问不在公共API中的方法的所有解决方案一样,我不能保证这不会破坏新版本的Android.