Search code examples
androidandroid-fragmentsonbackpressed

android activity onBackPressed not called


  @Override
public void onBackPressed() {
    if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
        FragmentManager.BackStackEntry bSE = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1);
        Fragment frag = getSupportFragmentManager().findFragmentByTag(bSE.getName());
        if (frag instanceof BackButtonBlocker)
        {
            BackButtonBlocker callback = (BackButtonBlocker) frag;
            callback.onBackPressed();
        }
        else {
            getSupportFragmentManager().popBackStack();
        }
    } else {
        super.onBackPressed();
    }
}

BackButtonBlocker interface is for callback. my fragment implements BackButtonBlocker but sometimes onBackPressed not occurs (onKeyUp as well).

when I open navigation drawer, onBackPressed and full logic works exactly.

why should activity lose focus?

android.support.v4.app.Fragment

public interface BackButtonBlocker{ void onBackPressed();}

Solution

  • I fixed this issue by adding setFocusableInTouchMode(true); requestFocus(); on Mainactivity's container view