问题
I use the following code to pop up the soft input keyboard in my Activity
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.getInputMethodList();
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
This displays the alphabetic keyboard.
But I want to display the numeric keyboard.
Please note I know that using setInputType() works when used with an Edittext or a TextView but I want to be able to display the keyboard without an input area such as an EditText and simply listen to the key presses on the keyboard.
Can anyone confirm whether this is possible and if so how can it be achieved?
回答1:
try using the "onKeyDown" methods, I use them for capturing the "back" hard key on phones in my application, an example of the method, using back as the button its listening for, would be
public boolean onKeyDown(int keyCode, KeyEvent event){
if((keyCode == KeyEvent.KEY_BACK)){
back();
}
return super.onKeyDown(keyCode,event);
}
But instead of using KeyEvent.KEY_BACK, try using KeyEvent.KEYCODE_P instead. I'm not possitive if this will work on a soft keyboard, but its worth a shot! good luck
回答2:
This is indeed achievable and possible.
TL;DR:
Override onCreateInputConnection
and request a numeric keypad:
public class CustomView extends View {
[your methods here]
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
InputConnection connection = super.onCreateInputConnection(outAttrs);
outAttrs.inputType |= InputType.TYPE_CLASS_NUMBER;
return connection;
}
}
Full Explanation
You've subclassed View
to create your own custom view:
public class CustomView extends View {
[your methods here]
}
Within this custom view, you're using the InputMethodManager to show the keyboard. This manager is going to delegate input to an InputConnection, which will then delegate to an InputMethod.
To request that they keyboard shown is numeric, you'll want to override onCreateInputConnection to return a numeric keypad. You could go to the trouble and implement your own BaseInputConnection, or you could just reuse the one created for you by super
(in this case, View
) and set the property you care about (inputType
).
来源:https://stackoverflow.com/questions/3980510/display-a-numeric-keypad-on-activity-without-an-input-area