如何从服务中显示软键盘

如何从服务中显示软键盘

本文介绍了如何从服务中显示软键盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简短的问题:是否可以(以及如何)通过服务"显示软键盘?

Short question: Is it possible (and how) to display the soft-keyboard from a Service?

常见问题:我编写了一个服务,该服务创建一个顶部栏",显示在所有活动的顶部,其中包含一个EditText.单击该EditText时,我想显示软键盘,但这没有发生.

Long question: I wrote a service which creates a "top bar", displayed on top of all activities, containing an EditText. I want to display the soft-keyboard when that EditText is clicked, but this is not happening.

我当然已经从服务的onFocusChange()和onClick()中尝试过此操作:

Of course I've tried this from the Service's onFocusChange() and onClick():

InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);

我想出的解决方法是通过扩展Activity类并添加AIDL接口来请求当前活动以显示键盘.缺点是必须将每个键事件(通过另一个AIDL接口)发送回服务并手动转换为Unicode.

The workaround I came up with is to request the current activity to show the keyboard, by extending the Activity class and adding an AIDL interface. The drawback is that each key event has to be sent back to the Service (via another AIDL inteface) and manually converted into Unicode.

此外,如果当前活动包含EditText,则软键盘仅适用于该活动,并且在选择服务的EditText时不再显示.

Moreover, if the current activity contains an EditText, the soft-keyboard only works for the activity and doesn't show up anymore when the service's EditText is selected.

如果当前活动具有EditText,是什么导致无法显示服务的软键盘?可能是Android的限制吗?

What prevents the service's soft-keyboard to be displayed if the current activity has an EditText? Could it be an Android limitation?

推荐答案

我也遇到了类似的问题.我已经解决了.也许为时已晚,但可能对某人有所帮助.错误的可能原因:在LayoutParams中设置FLAG_NOT_FOCUSABLE

I have faced a similar issue. I have solved it now. Maybe it's too late but may it helps someone.Possible Cause of Error:Setting FLAG_NOT_FOCUSABLE during LayoutParams

只需将 FLAG_NOT_FOCUSABLE 替换为 0

使用以下代码:

InputMethodManager imm = null;

mView.findViewById(R.id.editText).setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    if(imm==null){
                        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    }

                    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0 );
                }
            }
        });

第二次创建LayoutParams

2nd When creating LayoutParams

private WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                    0,
                    PixelFormat.TRANSLUCENT);

这篇关于如何从服务中显示软键盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 20:08