onBackPressed()
will not get called when keyboard is shown and it gets closed. Don't know exact reason but it is a fact.
However, if you need to capture the back pressed event when keyboard is shown you can listen for the changes in root/parent layout visibility.
Restating @ReubenScratton who gave excellent answer to overcome this issue, we have this code:
final View activityRootView = findViewById(R.id.activityRoot);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
if (heightDiff > dpToPx(this, 200)) { // if more than 200 dp, it's probably a keyboard...
// ... do something here
}
}
});
and dpToPx
function:
public static float dpToPx(Context context, float valueInDp) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics);
}