Use the coordinatorLayout to scroll of the ActionBar
I’m going to show you how to use the new design library 22.2.0 to create an AppBar which is going to scroll of the screen while scrolling up.
With the new design library 22.2 you can create an Toolbar which is going to scroll of the screen. In this little tutorial I will show you how to achieve this with the AppBarLayout.
- First we create a new projekt with the minimum SDK API 14: Android 4.0 (IceCreamSandwich)
- We have a MainActivity extending from AppCombatActivity
- After that we add this line to the build.gradle (Module: app) under dependencies:
compile 'com.android.support:design:22.2.0'
- Our main_activity.xml should look like this:
- Your scrollable view could also be a RecyclerView. Otherwise it will not recognize the scrolling.
- You can also use following scrollFlags:
- scroll: this flag should be set for all views that want to scroll off the screen - for views that do not use this flag, they’ll remain pinned to the top of the screen
- enterAlways: this flag ensures that any downward scroll will cause this view to become visible, enabling the ‘quick return’ pattern
- enterAlwaysCollapsed: When your view has declared a minHeight and you use this flag, your View will only enter at its minimum height (i.e., ‘collapsed’), only re-expanding to its full height when the scrolling view has reached it’s top.
- exitUntilCollapsed: this flag causes the view to scroll off until it is ‘collapsed’ (its minHeight) before exiting
- Because we are using an AppBarOverlay we must use a style that hasn’t an ActionBar included. The styles.xml should look like this:
- In our MainActivity.java the onCreate method will set the toolbar as supportActionBar:
- With the support library you also can set a primary color, primary color dark and an acent color to define your unique app style. This happens in the styles.xml file:
You can find the full soure code on Github: https://github.com/BenedictP/AppBarScrollOffScreen