Search code examples
androidandroid-actionbarandroidxappcompatactivity

Hide Shadow on androidX Toolbar


I want to hide the shadow below the ActionBar to make the ActionBar look flat. There should be no line, shadow, border between ActionBar and the layout.

Constraints

  • Unfortunately I have a constraint that there must be an ActionBar involved. I cannot simply remove the ActionBar and set whitespace on the top of the screen.
  • Another constraint is that I want to toggle the visibility of the shadow at runtime from code.

What worked for me on the android.support.v7.widget.Toolbar does not work for me on the androidx.appcompat.widget.Toolbar.

I tried several things like

  • setting the supportActionBar's elevation to 0 has no effect at all

  • setting the elevation of the AppBarLayout to 0 has no effect at all

  • setting the elevation of the Toolbar to 0 has no effect at all

  • setting the alpha to 0 makes the ActionBar invisible but I need a visible and functioning UpButton

      <com.google.android.material.appbar.AppBarLayout
          android:id="@+id/appBarLayout"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">
    
          <androidx.appcompat.widget.Toolbar
              android:id="@+id/toolbar"
              android:layout_width="match_parent"
              android:layout_height="?attr/actionBarSize"/>
    
      </com.google.android.material.appbar.AppBarLayout>
    

So far nothing works for me.


Solution

  • The only thing that worked for me is to set the elevation of the AppBarLayout in code. Unfortunately in a Fragment you need to know in which Activity you are and need access to its AppBarLayout and that is something that makes the code ugly. In the future there should be a function for that in the SupportActionbar like show/hideShadow() or so.

    Long story short. What I did to hide/show the shadow of the ActionBar

    In your Activity

    appBarLayout.elevation = 0f
    

    In your Fragment

    if (requireActivity is MyActivity) {
        (activity as MyActivity).appBarLayout.elevation = 0f
    }
    

    Keep in mind that if you change the ActionBar from your Fragment, that all other Fragments hosted by the same Activity will see the changes too.

    Another problem is testing as in Espresso your Fragment will be launched in an EmptyActivity that has no AppBarLayout. But at least with the above code your App does not crash.