Search code examples
androidandroid-fragmentsandroid-fragmentactivityback-button

Back navigation in title bar - fragment


There are many questions like this asked but everything I have tried seems to not work. Essentially I have a main activity that calls different fragments depending on what the user clicks with the home fragment being default. I would like to have a back button on the title bar, to go back to the previous fragment.

My fragment is called from the main activity like so:

    Fragment fragment = null;
    fragment = new nextFragment();

    if (fragment != null) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        fragmentTransaction.replace(R.id.frame_container, fragment).addToBackStack(null);
        fragmentTransaction.commit();
        fragmentTransaction.addToBackStack(null);

    } else {
        // error in creating fragment
        Log.e("MainActivity", "Error in creating fragment");
    }

But since ActionBarActivity activity is deprecated I need to extend AppCompatActivity instead of FragmentActivity so I can use actionbar (I'm assuming this is what I need). However then I am unable to switch to my fragment. So does anyone know how I could implement a back button in my fragment or how to use AppCompatActivity in this situation. Thanks for any help.


Solution

  • Please try this if you extend AppCompatActivity:

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            //Include these 2 lines ONLY if need to use Toolbar from layout xml as Action Bar
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
            //Add back navigation in the title bar
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
            //
            //Other works to be done in onCreate.....
            //
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            if (item.getItemId() == android.R.id.home) {
                //Title bar back press triggers onBackPressed()
                onBackPressed();
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    
        //Both navigation bar back press and title bar back press will trigger this method
        @Override
        public void onBackPressed() {
            if (getFragmentManager().getBackStackEntryCount() > 0 ) { 
                getFragmentManager().popBackStack(); 
            } 
            else { 
                super.onBackPressed(); 
            }
        }
    }