View-specific IME?

2019-01-26 19:10发布

问题:

I have a custom view for which I want the user to be able to enter characters from an app-defined set of characters. To do this, as I understand it, I need to write an input method service. The user not only needs to install it, but then needs to enable the IME in the Settings > Language & keyboard, and then select the custom IME for use in the view.

This seems really crazy. I want this IME to be used for just one view in one application. I don't want it to be available system-wide or force the user to make global setting changes.

The only alternative I can see is defining my own in-app custom view and simulate an IME (probably a full-screen one) when the view gains focus. Isn't there anything better?

回答1:

I do not think the IMEs are conceived for that kind of task. Their concept is to allow user input in a standardized way so it can be used across multiple applications from different vendors.

My strategy would be similar to what you are thinking:

  • prevent the soft keyboard from appearing,
  • intercept the menu button key press to show your own instead,
  • add a custom layout (probably a GridView or a TableView inside a RelativeLayout with bottom gravity)
  • use an OnItemClickListener
  • send the required KeyEvents to the root View. If the characters are invented, the KeyCodes do not even need to relate to the ASCII character. You just intercept the code and use at will.

Sorry I can't give you an option as you asked, but this alternative does not seem to be much more work than creating a whole new IME.

Edit: upon reading the related question, it makes sense to use android.inputmethodservice.KeyboardView instead of reinventing the wheel with the GridView.