Search code examples
androidandroid-fragmentsnavigation-draweronbackpressed

Android back stack one fragment, when pressing hardware back button shows the back stacked one.


Android back stack one fragment, when pressing hardware back button shows the back stacked one.

Below is my expected scenario:

I have one activity with navigation drawer. Each navigation element navigate to different fragments on click. I want to back stack only the home fragment. when pressing back button from any other fragments , navigate to the home fragment. When pressing the back button from home fragment, app exits.


Solution

  • You can handle onBackPressed method in this method, comment the line //super.onBackPressed();

        @Override
            public void onBackPressed() {
    //            super.onBackPressed();
    //Now check if current fragment is not home fragment
    // then replace current fragment with home fragment
    //if current fragment is home fragment then execute the following code
    Intent homeIntent = new Intent(Intent.ACTION_MAIN);
        homeIntent.addCategory( Intent.CATEGORY_HOME );
        homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
        startActivity(homeIntent); 
    
            }