I have a EditText component, and, of course, if you click on it, the Android keypad is shown, allowing the user to input text. As far as I know, all Android software keyboards have (at least) a letter mode (ABC) and a symbols mode (?123). Their default view is the letter mode.
Now when the keypad is shown when the EditText component is clicked, I want the symbols mode to be shown by default. The user will still be able to switch to the letter mode.
Is there a way to achieve that? If yes, how?
I'm posting this because I don't think any of the answers actually address the question. The screenshot in the question does not correspond to a particular InputType's default state. So, switching InputTypes will not give you the layout from the screenshot.
(based on my research...)
Support for symbol input is not governed by any contract. One can very well leave symbols out when creating their own InputMethod. OR, they can add pagination support to provide access to 100s of symbols. Can this be bound by a contract? May be. But, it isn't at present.
Input method framework does not allow direct communication between the client and the IME. All communication happens either through the InputMethodManager or through InputConnection — a one-way channel. Switching to symbols using ?123 is, however, an internal event — not a defined state/action. Client applications cannot switch to it. There's no public (or hidden) API to make this happen.
InputType indicates something entirely different to an IME. Not sure why everyone is recommending its use. You may of course find that a particular InputType provides most of the required keys. But that isn't the same as show[ing] Android keyboard with symbols mode by default.
Possible workaround:
We'll create a custom EditText. We don't have to. It'll just keep everything in one place, and save us from copy-paste nightmare.
public class CusEditText extends EditText {
private final int mDefinedActionId;
public CusEditText(Context context, AttributeSet attrs) {
super(context, attrs);
// Corresponds to 'android:imeActionId' value
mDefinedActionId = getResources().getInteger(R.integer.definedActionId);
setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
Log.i("CusEditText", "onEditorAction, actionId = " + actionId);
// Only bother if (...)
if (actionId == mDefinedActionId) {
// Check if current InputType is NUMBER
if ((getInputType() & InputType.TYPE_CLASS_NUMBER) != 0) {
// Toggle
setImeActionLabel("NUM", mDefinedActionId);
setInputType(InputType.TYPE_CLASS_TEXT);
} else {
// Current InputType is TEXT // Toggle
setImeActionLabel("ABC", mDefinedActionId);
setInputType(InputType.TYPE_CLASS_NUMBER);
}
// We've handled this
return true;
}
// Let someone else worry about this
return false;
}
});
}
}
Next, we need to define definedActionId. Open or create res/values/integers.xml and add:
<integer name="definedActionId">-100</integer>
-100 is an arbitrary value. I checked EditorInfo and the actionIds (IME_ACTION_XXXX) were >= 0. -100 seems like a good candidate.
In xml, your layout will look like:
<com.your.packagename.CusEditText
android:layout_width="blah"
android:layout_height="blah"
android:inputType="number"
android:imeActionId="#integer/definedActionId"
android:imeActionLabel="ABC"/>
<!-- Probably use #string resource in place of ABC -->
There's not much to explain. IME will launch in NUMBER mode. Instead of a checkmark icon, it'll display ABC. On click, we intercept the actionId and toggle between NUMBER and TEXT input. We're using setInputType(...) because it not only updates the InputType, it also restarts the IME with changes. setRawInputType(...) only updates the InputType.
Issues:
As you can tell, this isn't really a solution. If the user closes the keyboard(using the back button) in TEXT mode, the keyboard will remain in the TEXT mode when they open it again. To go to the NUMBER mode, user will have to click NUM. Also, in TEXT mode, user will see NUM as the action, along with ?123 option. This doesn't break anything, but does take away from the UX.
We can't do anything about ?123 showing in TEXT mode for reasons listed above. But, we can try to make sure that the keyboard always opens in the NUMBER mode. I'll provide a rough sketch of how we'll do that. Its not straight-forward since we (developers) are not privy to events such as keyboard closing or opening. Updated CusEditText:
public class CusEditText extends EditText {
private final int mDefinedActionId;
private long mLastEditorActionTime = 0L;
public CusEditText(Context context, AttributeSet attrs) {
super(context, attrs);
// Corresponds to 'android:imeActionId' value
mDefinedActionId = getResources().getInteger(R.integer.definedActionId);
setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
Log.i("CusEditText", "onEditorAction, actionId = " + actionId);
// Only bother if (...)
if (actionId == mDefinedActionId) {
// setInputType(...) will restart the IME
// and call finishComposingText()
// see below
mLastEditorActionTime = SystemClock.elapsedRealtime();
// Check if current InputType is NUMBER
if ((getInputType() & InputType.TYPE_CLASS_NUMBER) != 0) {
// Toggle
setImeActionLabel("NUM", mDefinedActionId);
setInputType(InputType.TYPE_CLASS_TEXT);
} else {
// Current InputType is TEXT // Toggle
setImeActionLabel("ABC", mDefinedActionId);
setInputType(InputType.TYPE_CLASS_NUMBER);
}
// We've handled this
return true;
}
// Let someone else worry about this
return false;
}
});
}
#Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
InputConnection inputConnection = super.onCreateInputConnection(outAttrs);
return new CusInputConnectionWrapper(inputConnection, false);
}
private class CusInputConnectionWrapper extends InputConnectionWrapper {
private CusInputConnectionWrapper(InputConnection target, boolean mutable) {
super(target, mutable);
}
#Override
public boolean finishComposingText() {
Log.i("CICW", "finishComposingText");
// Ignore finishComposingText for 1 second (1000L)
if (SystemClock.elapsedRealtime() - mLastEditorActionTime > 1000L) {
if ((getInputType() & InputType.TYPE_CLASS_NUMBER) == 0) {
// InputConnection is no longer valid.
// Switch back to NUMBER iff required
setImeActionLabel("ABC", mDefinedActionId);
setInputType(InputType.TYPE_CLASS_NUMBER);
}
}
return super.finishComposingText();
}
}
}
Again, code is self-explanatory. We create a InputConnectionWrapper and listen for the finishComposingText() callback. If we're manually switching between TEXT and NUMBER, we use a flag since finishComposingText() will automatically be called. Else, we check if input type is set to TEXT and change it to NUMBER. I am not sure if finishComposingText() is the right method for interpreting keyboard closing/opening. Testing on API 21, vanilla android, this seems to work. More tests will be required.
I really hope someone can come up with a better, more robust solution than this - or modify my workaround so that it doesn't look like one.
Summary
Task at hand is to provide functionality of switching between NUMBER & TEXT input modes around existing Input Method Engines (IMEs). The first approach was to use imeActionLabel & imeActionId in the switching mechanism. This approach worked well with Google's keyboard (this is the imeActionLabel), but failed with Samsung's - imeActionLabel failed to show up in portrait (without extract). Possible workaround is to include the toggle button in the app's own UI.
Even with Google's keyboard, the letters (text) fail to show up when the mode switches back to NUMBER after inputting letters. This problem was fixed (at least on tested devices) by using flag flagNoExtractUi which prevents the IME from entering fullscreen mode in landscape orientation.
Final solution (pending implementation & testing)
The IME starts in the NUMBER input mode (95% use-cases involve number input)
A button is added to app's UI (next to the EditText) for switching between NUMBER & TEXT mode
User can switch from NUMBER to TEXT without any restrictions. Switching back from TEXT to NUMBER requires that no alphabets have been added.
InputType is preserved between keyboard closing & reopening. Example: If the user switches to TEXT mode and closes the keyboard, it will open in the TEXT mode. The InputType is not reset.
For more information about the approaches tried, refer to this discussion thread.
Screenshots
Default (NUMBER):
Switched to TEXT:
Recorded video link
I agree it is an InputType. If you want to show only numbers to your user then you would add the following to you xml document for your edit text:
android:inputType="number"
However if you set it as number then the user has to enter a number. But you can add additional types as well like numbers and email addresses such as:
android:inputType="number|textEmailAddress"
Check out http://developer.android.com/reference/android/text/InputType.html for more options. You can also check out what eclipse or android studio shows you under "inputType"
I believe you are looking to set the InputType of your edit text.
http://developer.android.com/reference/android/text/InputType.html
I'm not sure which you would use though you may have to play around a bit.
The only way to do this is by setting the inputType of your EditText.
If you want to set this property in the onCreate() (or inside a custom View's constructor) you can use the method setRawInputType():
mEditText.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
Otherwise, if you need to set this property after the onCreate() (or after a custom View's constructor), you can use the method setInputType():
mEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
Obviously you can also specify the property at XML level:
android:inputType="number|numberDecimal"
You can play around with different flags to find the best composed filter.
Programmatically it is possible with little bit of tweak to the usual flow. First you have to set editText as:
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
Then you have to listen for keyevent. On pressing of pound set the InputType again to InputType.TYPE_CLASS_TEXT. This should work as it works for me.
editText.setOnKeyListener(new View.OnKeyListener()
{
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
Log.d("KeyBoard", "Keyboard Test Key Hit");
switch (keyCode) {
KeyEvent.KEYCODE_POUND:
if(editText.setInputType(InputType.TYPE_CLASS_TEXT);
{
editText.setInputType(InputType.TYPE_CLASS_TEXT);
return true;
}
Same thing I've answered i: EditText with number keypad by default, but allowing alphabetic characters
Related
I've spent most of the day searching and trying various solutions and while I've come most of the way, I'm cursed by the "close" (maybe it has more appropriate name, idk) button on the nav bar when the keyboard is displayed (as in the attached image.)
I have a few editTexts which allow the user to adjust some parameters before a graph is recomputed and redrawn. I need to know when their input is complete. I've managed to sort out the "Done" button but for the life of me I can't figure out how to handle hitting that close button. I've also adapted some code which determines if the keyboard was opened and then closed (which is the case with these editTexts) but it only works when using the Done button (so is somewhat redundant).
So.. is there some way of picking up when the user has closed the keyboard using the nav bar?
TIA
Well, I think I have something here, perhaps it will be useful to others. Who knows how long it will work properly.
So prelude: I needed to be able to tell when a user had completed changing an edit text so that I could then redo a computation and update a graph. I really have no room for an "update" button and felt from a UI standpoint it would have quickly become annoying.
Codewise:
I have a "display" method with an inner "watcher" class with a watch() method. The watcher class has many things, including the various editTexts which watch()..watches. I ddapted some code I found here, which determines if the keyboard is open or closed. currentView is the root view of the graphing activity.
currentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
Rect r = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
int screenHeight = getWindow().getDecorView().getRootView().getHeight();
int heightDifference = screenHeight - (r.bottom - r.top);
if (MainActivity.debug) Log.d("Keyboard Size", "Size: " + heightDifference+" screenHeight: "+screenHeight);
boolean keyboardVisible = heightDifference > (screenHeight / 3);
if (keyboardToggle) { // someone has updated one of the editTexts
if(!keyboardVisible) { // and they have closed the soft keyboard so are done
// do something
if(MainActivity.debug) {
if(rIDchangedET == firstET.getId()) Log.i(TAG,"update the first thing");
if(rIDchangedET == secondET.getId()) Log.i(TAG,"update the second thing");
if(rIDchangedET == thirdET.getId()) Log.i(TAG,"update the third thing");
}
// reset the keyboard toggle
keyboardToggle = false;
}
}
}
});
This helps but in a somewhat backward way. Knowing open/closed by itself is not useful within any of the text watchers as those are not triggered by the act of closing the keyboard (so you can't actually test for it within the listener)
However, thinking about it a bit I added a boolean keyboard toggle which is set to true in the afterTextChanged of the addTextChangedListener. In addition, I put the rID of that editText in another class variable.
The code which checks the keyboard status then calls the appropriate updating procedure if the a) keyboard is closed b) some text has actually been changed (keyboard toggle) and c) uses the rID to determine what procedure to then call.
I know its a bit convoluted, but it does seem to work.
I'm quite new to Android native development, and I'm trying to figure out how to customize the IME action buttons. I've looked at the Google documentation, but I can find very few information about the expected behaviour.
From the offical guide I understand that the keyboard action button can be configured using the attributes:
android:imeOptions can set the text/id of the button displayed near the space key to some pre-defined values (E.g. actionGo set the key label to Go and the id to 2)
android:imeActionLabel set the label of the button displayed inside the input area when the keyboard is fullscreen, usually in landscape mode. Can be set to any string value.
android:imeActionId same as previous but set the numeric Id passed to the callback method
But after some empiric attempts I've found different behaviour between API level 15 and next API levels.
I've set up a simple EditText element with the following attributes:
<EditText
...
android:imeOptions="actionGo"
android:imeActionLabel="Custom"
android:imeActionId="666"
android:inputType="text"/>
and I've checked the effect with the different API levels both in portrait and landscape mode. Here is the outcome.
API level 15 - 4.0.3
In portrait mode the key label is Go and the action id passed to the callback method is 2, accordingly to the imeOptions setting.
In landscape mode the key label/id is Go/2 as the portrait mode, while the button displayed in the input area is Custom/666, accordingly to the imeActionLabel and imeActionId attributes.
API level 16, 17 and 18 - 4.1.2, 4.2.2 and 4.3
Both in portrait and landscape mode the key and the button are displayed with Custom label and are bound to 666 id, ignoring imeOptions attribute.
This mismatch in the behaviour is quite annoying because:
with API level >= 16 you can't distinguish between key button and input area button
with API level = 15 you can't set any custom text for key button.
Do you know how to obtain this both in API 15 and 16+?
Or if there is a way to obtain a consistent behaviour across all (or at least a part of) the API versions?
Maybe I am missing something in the IME settings that can justify the different behaviour...
Thank you very much!
It's actually up to the input method app, not the Android framework itself, to decide what to do with the values you set.
The Android framework just passes the values you set through to the input method, which can then choose what buttons to show on the keyboard or an "extracted" EditText in full-screen view. The Android framework influences the EditorInfo in two ways:-
It passes it through EditorInfo.makeCompatible to ensure the values therein are compatible between the keyboard's and the app's targetApiVersions. At the moment this only affects some InputType values, not the editor action, but this could change if new editor actions (or completely new settings) are introduced.
It sets the default behaviour for the input method, including the behaviour around full-screen editors. If the input method chooses not to override this default behaviour, then it could end up with behaviour that's different between Android versions. Many keyboards do choose to set their own behaviour, in a way that's consistent between Android versions.
For that reason, it's not so simple to say that a certain EditorInfo field has a certain effect on any given version, and there's no way to ensure a consistent behaviour, even on one Android version. All you're doing is providing hints to the input method, which chooses how to present them to the user.
Just call .setImeActionLabel() programtically in java codes to set actionID (again) to your desired one.
editText.setImeActionLabel(getString(R.string.xxx), EditorInfo.IME_ACTION_GO);
When you start a new Android project, it provides a good hint to your question. There is an Activity called LoginActivity which you can create as a default login screen. This Activity will produce an EditText as so:
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_password"
android:imeActionId="#+id/login"
android:imeActionLabel="#string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true"/>
Now if you read the documentation, you would know that the imeOptions attribute allows you to specify additional actions for a text field. For example, the keyboard that pops up has an action on the bottom right corner like "Next". Using imeOptions you can select another action from a predefined list provided by Android. You can specify something like "actionSend" or "actionSearch".
Once you do that, in order you Activity, you can listen for that action using the setOnEditorActionListener event handler:
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Notice how we target the imeActionId here. It is another method to target that EditText in your Activity, while also having the flexibility to change the action on the keyboard input.
If someone is designing a custom keyboard for Android and has a problem with the label of the Enter key, you should do the following. In the sample of Android custom keyboard we have the following method in SoftKeyboard.java:
#Override
public void onStartInput(EditorInfo attribute, boolean restarting)
{
super.onStartInput(attribute, restarting);
.
. // the implementation
.
mCurKeyboard.setImeOptions(getResources(), attribute.imeOptions);
}
Change the last line to the following line:
mCurKeyboard.setImeOptions(getResources(), attribute);
Now in LatinKeyboard.java change setImeOptions method like bellow:
void setImeOptions(Resources res, EditorInfo ei)
{
if (mEnterKey == null)
{
return;
}
switch (ei.imeOptions & (EditorInfo.IME_MASK_ACTION | EditorInfo.IME_FLAG_NO_ENTER_ACTION))
{
case EditorInfo.IME_ACTION_SEND:
mEnterKey.iconPreview = null;
mEnterKey.icon = null;
mEnterKey.label = res.getText(R.string.label_send_key);
break;
case EditorInfo.IME_ACTION_GO:
mEnterKey.iconPreview = null;
mEnterKey.icon = null;
mEnterKey.label = res.getText(R.string.label_go_key);
break;
case EditorInfo.IME_ACTION_NEXT:
mEnterKey.iconPreview = null;
mEnterKey.icon = null;
mEnterKey.label = res.getText(R.string.label_next_key);
break;
case EditorInfo.IME_ACTION_SEARCH:
mEnterKey.icon = res.getDrawable(R.drawable.sym_keyboard_search);
mEnterKey.label = null;
break;
default:
mEnterKey.iconPreview = null;
mEnterKey.label = res.getText(R.string.label_enter_key);
mEnterKey.icon = null;
break;
}
if (ei.actionLabel != null)
{
mEnterKey.iconPreview = null;
mEnterKey.icon = null;
mEnterKey.label = ei.actionLabel;
}
}
Now your custom keyboard shows proper label based on what is defined in xml file for imeActionLabel.
thanks for any help up front. I will admit ahead of time that my Java is still immature, so I feel like I'm in over my head. I've been searching almost all day for this answer and trying various approaches to no avail.
I am using a commercial game engine which exports a game to an Eclipse project with a GLSurfaceView class implementation. They have a hook to send single key codes into the game engine for key down and key up events, and I want to use those hooks to send keys from the Android keyboard (soft or hard).
Overriding the view.onKeyUp, onKeyDown, and onKeyMultiple interfaces allows me to get almost everything I'm looking to do, but when an IME like Swype is used, I still have one remaining problem.
When I swype the word, it shows up in the floating window (I believe swype is drawing this), but then it doesn't come across in the onKeyUp, onKeyDown, or onKeyMultiple callbacks. If I hit space or any other letter on the keyboard, I then get the onKeyMultiple callback which sends the string I swyped previously.
I thought I could just call finishComposingText() in my own InputConnection, so I overrode the View.onCreateInputConnection method in the GLSurfaceView class, and then called finishComposingText() in the DrawFrame() method for the game engine, and it worked somewhat. It actually immediately sent the text through the onKeyMultiple callback, but then if I hit a key, it sent the same text again, duplicating it in my "3D edit box". I also didn't like the idea of calling that every frame.
I'm just completely lost on what approach I should take to get the swype results to show up instantly after I swype without having to press a key. The game engine is not using a TextView or similar Android widget, so I tried the following as well with no luck:
public InputConnection onCreateInputConnection ( EditorInfo outAttrs )
{
outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE ;
outAttrs.inputType = InputType.TYPE_NULL;
oInputC = new BaseInputConnection ( this, false ) ;
return oInputC;
}
oInputC is just a static variable I can use to call the finishComposingText() method.
Could anyone suggest an approach or reference? I have found only a couple of other questions like this, and they were both unanswered. It seems not many people are creating their own text edit boxes and need to implement the backend for them, but that's essentially what I need to do.
I am facing the same issue, but I think I have found solution.
I was checking android source code of TextView and EditableInputConnection to see how they are doing: it turns out that's its not so easy.
I think I managed to make it work correctly, with my custom editor. This is how my input connection looks like.
#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_UNSPECIFIED | EditorInfo.IME_FLAG_NO_EXTRACT_UI;
outAttrs.inputType = InputType.TYPE_CLASS_TEXT;
final InputConnection in = new BaseInputConnection(this, false){
private HudInputElement getInputElement(){...}
#Override
public boolean setComposingText(CharSequence text,
int newCursorPosition) {
B2DEngine.getLogger().info("composing text: "+text+","+newCursorPosition);
HudInputElement input = getInputElement();
if(input!=null){
input.setComposingText(text.toString());
}
return super.setComposingText(text, newCursorPosition);
}
#Override
public boolean finishComposingText() {
HudInputElement input = getInputElement();
if(input!=null){
input.doneComposing();
}
return super.finishComposingText();
}
#Override
public boolean commitText(CharSequence text, int newCursorPosition) {
B2DEngine.getLogger().info("commit:"+text.toString()+","+this.getEditable().toString());
HudInputElement input = getInputElement();
if(input!=null){
input.doneComposing();
}
return super.commitText(text, newCursorPosition);
}
};
return in;
}
Since soft input keyboards supports all sorts of way to autocomplete text, currently entered word is treated differently. You have to ensure that when setComposingText is called, you have to replace the text that was previously received. Only clear this flag when user presses a button or finishComposingText or commitText are called.
P.S. Don't forget to test other keyboards on the market.
Is there any way to show software keyboard with USB keyboard connected (in my case RFID reader)?
I tried to force show it using InputManager (with these or similar parameters), but with no luck
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
Important notice - I know that there is a button in status/system bar to show it, but this button is not visible to user (Kiosk app).
You need to override the InputMethodService method onEvaluateInputViewShown() to evaluate to true even when there is a hard keyboard. See onEvaluateInputShown() and the Soft Input View section of InputMethodService. Try creating your own custom InputMethodService class to override this method.
EDIT: The source for onEvaluateInputShown() should help. The solution should be as simple as creating your own class that extends InputMethodService and overriding this one method, which is only a couple of lines long. Make sure to add your custom service to your manifest as well.
From Source:
"Override this to control when the soft input area should be shown to the user. The default implementation only shows the input view when there is no hard keyboard or the keyboard is hidden. If you change what this returns, you will need to call updateInputViewShown() yourself whenever the returned value may have changed to have it re-evalauted and applied."
public boolean onEvaluateInputViewShown() {
Configuration config = getResources().getConfiguration();
return config.keyboard == Configuration.KEYBOARD_NOKEYS
|| config.hardKeyboardHidden == Configuration.KEYBOARDHIDDEN_YES;
}
Here are the possible configurations you can check for. Configuration.KEYBOARD_NOKEYS corresponds to no hardware keyboard. This method returns true (soft keyboard should be shown) if there is no hardware keyboard or if the hardware keyboard is hidden. Removing both of these checks and simply returning true should make the software keyboard visible even if a hardware keyboard is attached.
Try (not tested):
public boolean onEvaluateInputViewShown() {
return true;
}
Since this return value will not change, you won't need to call updateInputViewShown() yourself. If you modify this method differently, be sure to remember this detail.
The soft keyboard can have unpredictable behaviour on different platforms. First in your code, ensure you have an editable input control. Eg, if you have an EditText, you could use:
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE))
.showSoftInput(myEditText, InputMethodManager.SHOW_FORCED);
However, you can just show and hide it whenever you want using:
//show keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//hide keyboard :
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
You could also add any of these events inside OnCreate or some other method of the controls.
If however for some reason any of the above fails, your best option might be to use an alternative keyboard, e.g. Compass Keyboard,
OR
You could even build yours:
See an example of a keyboard implementing the inputmethodservice.KeyboardView
You might also want to take a look at the GingerBread Keyboard source.
If your app has the WRITE_SECURE_SETTINGS permission (available to system apps or Android Things apps) it can set the show_ime_with_hard_keyboard system setting which will enable soft keyboard even if a hard keyboard is plugged:
Settings.Secure.putInt(getContentResolver(), "show_ime_with_hard_keyboard", 1);
This worked in my app, interestingly, also an kiosk app.
This is a bit stripped, I did some checks beforehand, whether IMM is null and such.
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInputFromWindow(someInputView.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
according to this https://stackoverflow.com/a/24287780/2233069, I made working solution for Kiosk mode.
boolean hardwareKeyboardPlugged=false;
....
mEditText.setOnFocusChangeListener(this);//in onCreate()
....
#Override
public void onResume() {
//protect from barcode scanner overriding keys
hardwareKeyboardPlugged=(getResources().getConfiguration().hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO);
super.onResume();
}
....
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
if (hardwareKeyboardPlugged){
//protect from barcode scanner overriding keys
hardwareKeyboardPlugged=false;
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).showInputMethodPicker();
Toast.makeText(this, "USB device detected. Turn OFF hardware keyboard to enable soft keyboard!", Toast.LENGTH_LONG).show();
}
}
We are working on our first android app and it has been a very enjoyable experience so far. It is almost complete, but before release we are having some considerations ,mainly about android soft keyboard.
We have a couple of EditText fields that are used to enter numbers. We would like to capture the event when user presses enter, and do some calcuations and saving on this callback.
The problem is that we are not getting a fixed event as different phones have different keyboards. Some have 'Done' button and our HTC phones have 'Enter' buttons. We tried using the imeOptions as 'done' but that had no effect on the HTC phones.
We also know that the keyboard can be dismissed by hitting the back button. So my question is if there is a reliable way to know when the user has stopped entering or when the keyboard is hidden, just like textFieldShouldReturn callback in iphone sdk(which will always fire when keyboard goes down, independent of what key caused it to go down)..
In other words, how an android developer handles soft keyboard? I check for KeyEvent.KEYCODE_ENTER on editText onClick() event and do my tasks there.It is working on my HTC android, but not on my friends Nexus phone, which has a done button instead of enter. There onClick is not even called. How a developer handles this?
EDIT: After losing half of my hair, and with the help of some good friends here
I have tried all your suggestions but at the end by using onEditorActionListener along with onKeyListener method did the trick for me. In onEdit callback of onEditorActionListener I checked for KeyCode ACTION_DONE, which did get called on keyboards with done button. On keyboards which has enter onKey gets called. In onKey method I checked for KEYCODE_BACK also, so that hardware back press event also can be handled. I haven't yet found out a android device with done and enter on the keyboard (seriously), still I even handled that case with a flag. Thanks #Femi for suggesting onEditorActionListener, and thanks for all friends for your help. But the answer to my original question
Q: Is there an reliable and easier way to know android soft keyboard resigns (callback that works on every phone)
Ans : No, All methods suggested here and all methods suggested on other sites are not straightforward. And I think handling an event for keyboard return key is the most basic thing for any operating system. Google, are you there?
Since it seems that you are catching the KEYCODE_ENTER event, you might be able to use this: http://developer.android.com/reference/android/widget/TextView.html#setOnEditorActionListener%28android.widget.TextView.OnEditorActionListener%29. In theory this will let you detect whatever the input method end action is (whether its back, done, enter, or whatever) and respond to it.
Let me know if that works for you.
Wouldn't you also need to perform those calculations when the user is leaving the TextView on a hardware keyboard? I wouldn't focus on the keyboard, but on the TextView itself. If so, what you probably want is setTransformationMethod
You'd have to implement a custom TransformationMethod, specifically the method getTransformation, which transforms a source CharSequence into another one. You can then use the onFocusChanged to apply this only when the focus is lost for that TextView.
I found a solution on this SO page:
Intercept back button from soft keyboard
The answer from mhradek has 0 votes but it seems to be working.
The idea is to extend the base layout of your activity so that you can override the dispatchKeyEventPreIme method and do what you want regarding the KeyEvent passed. Note that you are responsible for managing the soft keyboard.
I am using it and I can definitely intercept key strokes (the back button for example) without the soft keyboard "eating" them. I have yet to play more with it in order to see what is possible and what is not.
I hope it helps.
Have you tried implementing custom EditText view, where you override dispatchKeyEventPreIme? Just like in answer posted by Arnaud (referencing Intercept back button from soft keyboard) but instead of using custom layout use custom EditText and override:
#Override
public boolean dispatchKeyEventPreIme(KeyEvent event) {
if(KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
//this hides soft keyboard in super.dispatchKeyEventPreIme(event)
}
return super.dispatchKeyEventPreIme(event);
}
I suggested this solution in this question
I cant believe Google doesnt have a keyboard independant callback for this case
Wow, I cant believe that neither. I am having a similar problem at the moment.
In addition to the IME ACTION I check for focus changes on the EditFields. This is fine for most of the time, but won't work always.
I found a way to be notified when the keyboard is being hidden, but it's not a complete solution yet (and I'm not sure whether it's a good idea), but I don't have the time to continue right now, so I thought I can drop the start of the idea here...:
Write your own EditText(extend EditText) and override onCreateInputConnection. In your onCreateInputConnection return your own implementation of InputConnection (you can simply extend BasicInputConnection.
The InputConnections "finishComposingText()" method is always called when the keyboard is being hidden (also when the user presses the back-key).
This is the code, and maybe someone else has an idea, why the entered text is not shown in this editfield ;-)
public class MyEditText extends EditText{
public MyEditText(Context context) {
super(context);
}
public MyEditText(Context context, AttributeSet attrs) {
super(context);
}
public MyEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
System.out.println("onCreateInputConnection, "+outAttrs.actionId);
return new MyInputConnection(this,true);
}
private class MyInputConnection extends BaseInputConnection{
public MyInputConnection(View targetView, boolean fullEditor) {
super(targetView, fullEditor);
}
#Override
public boolean finishComposingText() {
System.out.println("FINISH");
return super.finishComposingText();
}
}
}
JPM
I have not tried this but, reading the documentation, it seems possible.
// From an activity, you can call
if (getResources().getConfiguration().keyboardHidden == Configuration.KEYBOARDHIDDEN_YES) {
// your code here
}
This code is working fine for me with HTC and default Android keyboard:
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// handle enter key on keyboard
if (actionId == EditorInfo.IME_ACTION_SEND ||
(event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN)) {
if (uid != null) {
// hide keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
// perform other stuff
return true;
}
}
return false;
}
});
Using the following in the editText´s XML:
android:imeOptions="actionSend"
Of course you could also use something else like send, just make sure to change it in both the XML and Java code.