11

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?

Zain
  • 37,492
  • 7
  • 60
  • 84
taha naqvi
  • 145
  • 1
  • 10

1 Answers1

19

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();
}
Zain
  • 37,492
  • 7
  • 60
  • 84
  • 2
    It is working, but when you come to that fragment where you want to hide the actionbar it is showing actionbar for a while and hide it with default animation – taha naqvi Apr 26 '20 at 16:27
  • @tahanaqvi welcome.. for the animation issue; you can disable it with `supportActionBar.setShowHideAnimationEnabled(false);` – Zain Apr 26 '20 at 16:35
  • There is another problem, when you hide the actionbar, minimize the application and come back.. empty white space at the bottom of the screen having height of action bar is shown – taha naqvi Apr 26 '20 at 16:49
  • @tahanaqvi can you illustrate more especially with a picture .. I can't reproduce this issue in my testing app – Zain Apr 26 '20 at 16:53
  • I am unable to produce it again... I'll come to you again If I will get that issue :p Anyways, thanks – taha naqvi Apr 26 '20 at 16:56
  • Yes, but there is a red underline on it which is saying "ActionBar:setShowHideAnimationEnabled can only be called within the same library prefix" – taha naqvi Apr 26 '20 at 17:06
  • @tahanaqvi this is a bug, you can solve it using [this answer](https://stackoverflow.com/questions/41150995/appcompatactivity-oncreate-can-only-be-called-from-within-the-same-library-group#answer-41251316) – Zain Apr 26 '20 at 17:10
  • 1
    Be careful with this, there are certain situations where onStart of the next Fragment can be called before onStop of the previous fragment, thus leaving you with an ActionBar when you don't want one – Smalls Dec 04 '20 at 20:56
  • setShowHideAnimationEnabled doesn't seem to fix the action bar pop in for me – Chucky Jan 31 '22 at 17:44
  • Hi @Chucky it's a bit old; pls try to do the same in `navController.addOnDestinationChangedListener` by checking fragment Id; hopefully helps – Zain Feb 03 '22 at 14:26