Search code examples
javaandroidandroid-fragmentsandroid-architecture-navigationandroid-navigation

How to hide actionbar in some fragments with Android Navigation Components?


I am using android navigation components to navigate fragments. I can easily set action bar by using this code in the Main Activity :

    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);

But If I want to hide the supportActionbar in some of the fragments then what should be the best approach?


Solution

  • For the fragments that you want to hide the SupportActionBar, you can hide it in onResume() with .hide(), and show it again in onStop() with .show()

    @Override
    public void onResume() {
        super.onResume();
        ActionBar supportActionBar = ((AppCompatActivity) requireActivity()).getSupportActionBar();
        if (supportActionBar != null)
            supportActionBar.hide();
    }
    
    @Override
    public void onStop() {
        super.onStop();
        ActionBar supportActionBar = ((AppCompatActivity) requireActivity()).getSupportActionBar();
        if (supportActionBar != null)
            supportActionBar.show();
    }