Search code examples
androidandroid-activityfragmentonbackpressed

implementing onbackpressed in android


i have activity1 takes me to activity2 that takes me to fragment. i would like from fragment to go back to activity2

public void onBackPressed() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

Solution

  • While adding fragment from activity2 add it to backstack like this

    getSupportFragmentManager().beginTransaction()
                               .replace(R.id.frame_layout, new SampleFragment())
                               .addToBackStack(SampleFragment.class.getSimpleName())
                               .commit();
    

    And onBackPressed check if the fragment is present in backstack and pop it

     @Override
    public void onBackPressed() {
        if(getSupportFragmentManager().getBackStackEntryCount()>0){
            Fragment fragment=getSupportFragmentManager().findFragmentById(R.id.YOUR_FRAME_LAYOUT_ID);
            if(fragment!=null && fragment.getClass().getSimpleName().equalsIgnoreCase(SampleFragment.class.getSimpleName())){
                getSupportFragmentManager().popBackStackImmediate();
            }
        }else {
            super.onBackPressed();
        }
    }