Hello first of all thanks for an interesting question. It made me experiment with code. Here I am describing my solution.
To find the solution I had to know two things
1. how to detect whether a softkeyboard is visible or not
2. How to set softkeyboard visible or hidden.
I got the solution in the following steps
after searching a bit I realized that the best solution of detecting a softkeyboardstate
(visible/hidden) is to use ViewTreeObserver. I am directly pointing to a so answer to know about it if you don't know. Here is the link.
and to set the softkeyboardstate
I just used Window.setSoftInputMode
method.
and to know a user interaction I override onUserInteraction
method
Kept two flag. one flag is to preserve keyboardstate
another is to know whether the application went to background or not
CODE:
1. variable declared
int lastDiff = 0;
volatile boolean flag = false;
volatile int flag2 = 0;
2. ViewTreeObserver
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
activityRootView.getWindowVisibleDisplayFrame(r);
int heightDiff = activityRootView.getRootView()
.getHeight() - (r.bottom - r.top);
if (lastDiff == heightDiff)
return;
lastDiff = heightDiff;
Log.i("aerfin","arefin "+lastDiff);
if (heightDiff > 100) { // if more than 100 pixels, its
// probably a keyboard...
flag2 = 0;
} else {
if (flag == false)
flag2 = 1;
}
}
});
3. Handling user interaction
@Override
public void onUserInteraction() {
super.onUserInteraction();
flag = true;
}
4. Finally onPause
and onResume
@Override
protected void onPause() {
super.onPause();
flag = true;
}
@Override
protected void onResume() {
flag = false;
switch (flag2) {
case 0:
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
break;
case 1:
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
break;
default:
break;
}
super.onResume();
}
Explanation:
Here I used two flags (flag2
and flag
). flag2
preserves the keyboardstate
and flag
preserves whether the application goes to background or is there any user interaction. flag
is used because when application goes to background then at first it hides the keyboard. Other things can be easily understood from the code above.
Test:
tested in s2(ics), desire s (ics), galaxy y (2.3.6)
Final comment:
I wrote the code quickly so might be missed some other optimization. Also there might be chance of exceptional cases. If the screen changes for some reasons other than keyboard then it might not be able to detect keyboard state.