How to Force Android Soft Keyboard Open from Native Code?

时间秒杀一切 提交于 2020-01-03 17:06:45

问题


I have a game that uses a callback to Java from C++ to force open the soft keyboard when the user touches the screen. The Java code is simply this:

this._inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

This has worked fine for a while but recently we've been receiving complaints from some Motorola Droid users that the soft keyboard fails to open for them. Since we've only recently started to get these complaints and it's a number of users I'm thinking it was some kind of update to those devices.

Is there a better way I can force the keyboard to open? All the links I find online talk about using textbox controls and such but my app is primarily C++ and doesn't use the standard controls at all.


回答1:


I don't know if this is related to your problem, but I was running into some issues using only InputMethodManager.toggleSoftInput() when devices would sometimes get "out of sync" and hide when I wanted to show and vice versa.

I've had some success by taking advantage of the fact that while IMM.showSoftInput() won't show a keyboard, IMM.hideSoftInputFromWindow() will reliably close one, so when I want to show a keyboard I now call IMM.hideSoftInputFromWindow() followed by IMM.toggleSoftInput(), and use IMM.hideSoftInputFromWindow() by itself to hide one.

[A day later...]

Writing the above yesterday made me rethink how I was dealing with the soft keyboard (I mean, showSoftinput() does work, just not the way we expected it to) and so here is a better way to do it:

First, you need to set up your view so that Android knows it can have a soft keyboard - described in the docs for InputMethodManager. In my case I have a single view derived from GLSurfaceView and so I added:

setFocusable(true);
setFocusableInTouchMode(true);

to the constructor and then the following 2 overrides:

@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs)
{
    outAttrs.actionLabel = "";
    outAttrs.hintText = "";
    outAttrs.initialCapsMode = 0;
    outAttrs.initialSelEnd = outAttrs.initialSelStart = -1;
    outAttrs.label = "";
    outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI;        
    outAttrs.inputType = InputType.TYPE_NULL;        

    return  new BaseInputConnection(this, false);       
}     

@Override
public boolean onCheckIsTextEditor ()
{
    return true;
}

Now I can show the keyboard with:

InputMethodManager mgr = (InputMethodManager)mActivity.getSystemService(Context.INPUT_METHOD_SERVICE); 
mgr.showSoftInput(mView, 0);

and the keypresses get reported via the view's onKeyUp() and onKeyDown() methods.

Hiding it is still done using hideSoftInputFromWindow()



来源:https://stackoverflow.com/questions/7407231/how-to-force-android-soft-keyboard-open-from-native-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!