2

What I tested:

In Android when the keyboard is not opened and we press back button. onBackPressed() event is fired

Question

SCENARIO-A: In Android when the keyboard is opened and we press back button. The keyboard gets closed. onBackPressed() is not fired

note: first time onBackPressed() is not called here ... Only if keyboard is not visible onBackPressed() is called

How to Programatically simulate SCENARIO-A

Devrath
  • 37,389
  • 47
  • 165
  • 245

2 Answers2

0

on BackKeyPress check whether the Soft keyboard is open by belowed snippet,if open then close it and prevent onBackPressed(),if not call onBackPressed()

final View activityRootView = findViewById(R.id.activityRoot);
    activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        Rect r = new Rect();
        //r will be populated with the coordinates of your view that area still visible.
        activityRootView.getWindowVisibleDisplayFrame(r);

        int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
        if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
            ... close soft keyboard from here
        }
     }
    }); 
Akshay Tilekar
  • 1,516
  • 2
  • 9
  • 22
0

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);
}
Community
  • 1
  • 1
Marat
  • 4,252
  • 4
  • 26
  • 52