Android offers you an overwhelming api loaded with tons of overridable functions representing typical events you may face as a mobile developer. That is the reason because you are not usually worry about catching and handling a new event that you have never meet before, you guess, normally right, those smart kids from Mountain View implemented an event handler sometime ago. Well, this is not the case of soft keyboard. It can be easily show and hide with convenient methods but there is not an implemented way of catching when user choose to hide it. Due to this limitations I coded a simple snippet that I hope it will be useful. It is available here. It is pretty easy to use.
/* Somewhere else in your code */ RelativeLayout mainLayout = findViewById(R.layout.main_layout); // You must use your root layout InputMethodManager im = (InputMethodManager) getSystemService(Service.INPUT_METHOD_SERVICE); /* Instantiate and pass a callback */ SoftKeyboard softKeyboard; softKeyboard = new SoftKeyboard(mainLayout, im); softKeyboard.setSoftKeyboardCallback(new SoftKeyboard.SoftKeyboardChanged() { @Override public void onSoftKeyboardHide() { // Code here } @Override public void onSoftKeyboardShow() { // Code here } }); /* Open or close the soft keyboard programatically */ softKeyboard.openSoftKeyboard(); softKeyboard.closeSoftKeyboard(); /* SoftKeyboard can catch keyboard events when an EditText gains focus and keyboard appears */ /* Prevent memory leaks: */ @Override public void onDestroy() { super.onDestroy(); softKeyboard.unRegisterSoftKeyboardCallback(); }
Besides this, you must add this line to your activity reference in your manifest.xml.
android:windowSoftInputMode="adjustResize"
While I were coding this snippet I encountered with another snipper which is pretty awesome. It is basically the same, involves subclassing your main layout but I think is a very elegant solution. Use which solution fits better with your needs. Happy coding!
UPDATE (06/15/14): This snippet has been updated with some improvements but It can be used in the same straightforward way and it handles keyboard events from EditText too
This snippet was too specific and it could not catch open keyboard events from EditText, it only worked if you opened and closed keyboard with provided functions and EditText opens keyboard as default behavior. Obviously this was a heavy shortcoming I did not notice before. So here it is my fix: The constructor of SoftKeyboard has been changed from:
public SoftKeyboard(View layout, InputMethodManager im)
to:
public SoftKeyboard(ViewGroup layout, InputMethodManager im)
This means it is necessary to pass a reference of main layout now. Maybe it is more strict now but it is necessary for something we are going to see next and, really, it was not working with whatever view.
SoftKeyboard class, when instantiated, it is going to try to get a reference, if possible, of every EditText available. This will allow it to handle focus changes when a EditText is selected and keyboard appears.
private void initEditTexts() { editTextList = new ArrayList<EditText>(); int childCount = layout.getChildCount(); for(int i=0;i<=childCount -1;i++) { View v = layout.getChildAt(i); if(v instanceof EditText) { EditText editText = (EditText) v; editText.setOnFocusChangeListener(this); editText.setCursorVisible(false); editTextList.add(editText); } } }
SoftKeyboard implements the interface View.OnFocusChangeListener to handle properly focus changes on our EditTexts.
@Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus && !isKeyboardShow) { layoutBottom = getLayoutCoordinates(); softKeyboardThread.keyboardOpened(); isKeyboardShow = true; tempView = v; } }
I noticed the resize process when keyboard appears through an EditText gaining focus has some differences and it was breaking the logic of the thread which is checking the bottom position of the layout. So i added this silly loop to handle it.
// When keyboard is opened from EditText, initial bottom location is greater than layoutBottom // and at some moment equals layoutBottom. // That broke the previous logic, so I added this new loop to handle this. while(currentBottomLocation >= layoutBottom) { currentBottomLocation = getLayoutCoordinates(); }
There are some minor changes too but I think these are the most important changes. I have tested it but nothing is 100% bugs-free. I would love read your feedback about this modification.
UPDATE (10/07/14): Thanks to Francesco Verheye(verheye.francesco@gmail.com) this snippet can handle EditTexts attached to nested subViews. initEditText modifications:
private void initEditTexts(ViewGroup viewgroup) { if(editTextList == null) editTextList = new ArrayList<EditText>(); int childCount = viewgroup.getChildCount(); for(int i=0; i<= childCount-1;i++) { View v = viewgroup.getChildAt(i); if(v instanceof ViewGroup) { initEditTexts((ViewGroup) v); } if(v instanceof EditText) { EditText editText = (EditText) v; editText.setOnFocusChangeListener(this); //editText.setCursorVisible(false); editTextList.add(editText); } } }
great! I’ve been struggling with this issue for some time now. Never had the time to figure out to hide that thing 😛
Glad you liked it! 🙂
Translated this to C# for use with Xamarin, when softKeyboard.openSoftKeyboard() or
softKeyboard.closeSoftKeyboard() is called the keyboard shows/hides and the respective event is called in the SoftKeyboardChanged class. When the user touches an edittext however and the keyboard pops up by itsself no events are triggered, is this expectedbehaviour or am I doing something wrong here?? Using Android 4.3
Correction: Even when opening and closing the keyboard using only softKeyboard.openSoftKeyboard() and softKeyboard.closeSoftKeyboard(), onSoftKeyboardShow is called but onSoftKeyboardHide is never called (the keyboard closes but the while loop looking for the closed keyboard just keeps on going). When I open the keyboard a second time, the while loop (still) looking for the closed keyboard exits, calls onSoftKeyboardHide and immedeately after that onSoftKeyboardShow is called as well.
In other words, onSoftKeyboardHide is only called the second time the keyboard is opened using softKeyboard.openSoftKeyboard(), immedeately followed but onSoftKeyboardShow.
Still investigating further…
Hi Rik,
That is weird, I got this snippet working in a native app and apparently is doing it fine. I am going to reproduce your scenario( EditText pressed) and other set of tests.
I dont know too much about Xamarin but I guess it should work. I will tell you soon.
Allrighty think I found the problem for onSoftKeyBoardHide not being called: the View i provided as a parameter in the SoftKeyboard constructor was not the root view of the app. Apparently the root view of the app is the only view that has properties changed when the keyboard appears/dissapears, and as such is the only view that can be used to determine whether the keyboard is opened/closed.
So you may want to change your comment on line 4 of your snippet to “// You can use this snippet with whatever kind of View as long as it is the root view of your app”.
So that problem was pretty much just me being careless in translating/implementing your code (woops). There is another problem with this code though, if the keyboard isnt opened by calling openSoftKeyboard() in your SoftKeyboard class, none of the events get called and the code doesnt work. So unless I’m missing something here (and please tell me if I am) you have to hook up all your edittexts to show the SofKeyboard by calling openSoftKeyboard() instead of the standard keyboard-opening behaviour. I use the following method to do this, it’s in C# but can easily be translated to Java:
public void EditTextAttachSoftKeyboard(EditText edittext)
{
// Make the keyboard appear
edittext.FocusChange += delegate(object sender, View.FocusChangeEventArgs args)
{
// NOTE By setting the on focus listener, we can show the keyboard when the edit box gets focus, but also hide it when the edit box loses focus
if (args.HasFocus)
{
softKeyboard.OpenSoftKeyboard();
} else {
softKeyboard.CloseSoftKeyboard();
}
};
edittext.Click += delegate(object sender, EventArgs args)
{
// NOTE By setting the on click listener, we can show the keyboard again, by tapping on an edit box that already had focus (but that had the keyboard hidden).
softKeyboard.OpenSoftKeyboard();
};
// Disable standard keyboard hard way
// NOTE There is also an easy way: ‘edittext.setInputType(InputType.TYPE_NULL)’ (but you will not have a cursor, and no ‘edittext.setCursorVisible(true)’ doesn’t work )
edittext.Touch += delegate(object sender, View.TouchEventArgs args)
{
EditText edittext2 = (EditText)sender;
int inType = (int)edittext2.InputType; // Backup the input type
edittext2.InputType = InputTypes.Null; // Disable standard keyboard
edittext2.OnTouchEvent(args.Event); // Call native handler
edittext2.InputType = (InputTypes)inType; // Restore input type
};
}
Above code was adapted from a custom keyboard tutorial: http://www.fampennings.nl/maarten/android/09keyboard/index.htm. It does have some small drawbacks such as the cursor not flickering, you can read more about it on the provided page,
A last note for people trying to translate the code on this blog to C# for Xamarin:
You can replace the synchronized wait and notify Java code with C# Monitor.Wait and Monitor.Pulse inside lock(this) statements.
Allrighty, looks like the code i posted still has some bugs, guess I shouldnt be in such a hurry to post ><. Will post updated code asap!
Hi Rik,
You were right about the problems of this snippet:
– The root Layout is required and It was not guaranteed if you provided a different view was going to work.
– I did not think about supporting EditTexts show keyboard events when they gained focus. But that was a good point I missed completely.
So following your good ideas I have modified the snippet and now it can catch open/close keyboard events when an EditText gain focus.
I updated the post and I would love to hear your opinion, feedback or whatever bug you encountered in this new version.
🙂
Hey felhr, thanks for the reply, I’m working on some other issues at the moment but will get back to you asap!
Nice!
I made a changement to that it works for all nested subviews.
private void initEditTexts(ViewGroup viewgroup) {
if (editTextList == null) {
editTextList = new ArrayList();
}
int childCount = viewgroup.getChildCount();
for (int i = 0; i <= childCount – 1; i++) {
View v = viewgroup.getChildAt(i);
if (v instanceof ViewGroup) {
initEditTexts((ViewGroup) v);
}
if (v instanceof EditText) {
EditText editText = (EditText) v;
editText.setOnFocusChangeListener(this);
// editText.setCursorVisible(false);
editTextList.add(editText);
}
}
}
Hello Francesco, great idea you brought here! 🙂
I have tested your changes and they had a little problem I solved:
initEditTexts used to instantiate a new ArrayList of EditText. As you are cleverly using recursion, editTextList was being instantiate every function call. That gave me some problems in my tests. I basically have moved editTextList editTextList = new ArrayList(); out of there and it works. I am going to add your commit and mention you if you dont mind.
Thank you very much ! 🙂
Np. In my little test app i had no errors or problems.
Yeah, I have changed your editTextList = new ArrayList(); to editTextList = new ArrayList(); and it works now. Not a recursion problem. I am going to add your changes and mention you if you dont mind. Thanks 🙂
That’s fine for me. I have to say that I have my own working class now (75 lines).
Interested: contact verheye.francesco@gmail.com
Post updated!
Sorry but this solution doesnt working for me on android 5.1. when opening up the soft keyboard then the onShow calling then immediatelly the onHidden. When I hide the soft kb nothing is happening…
Hi Laca,
Are your app running on Landscape mode?
My orientation is not fixed
So..Does it fail in both orientation? I noticed some bugs in landscape. Please confirm this and I will try to solve. Thanks 🙂
great job. You pointed me into right direction
Thankyou so much for this!
Suggestion: please edit your sample usage line 4:
RelativeLayout mainLayout = findViewById(R.layout.main_layout)
Since it is no longer valid, and avoids relative newbies (like myself) spending a few hours trying implement something that will no longer work. Thankyou 🙂
Hi!
What line should be used instead?
so much thx