Let’s Talk About Toolbars
In our days it appears that Google is in a redesigns apps phase. It started with Google news, then messages and more are coming.
These newly redesigned apps trace the path for material design. Defining the UI and UX patterns for modern android applications.
One particular component that suffers recent changes was the toolbar widget. I am not talking about the center title and new font. I am talking about the elevation animation when the user scrolls.
Since the introduction of material design back in 2014, the habit was to define a 4dp elevation. That property was visible even when the user did not scroll or the content did not have enough content to scroll.
Well, the world has changed and we should only show it when the content goes beneath the widget.
So the question is: how to implement it?
Implementation
I am going to assume that you are using a RecyclerView or a NestedScrollView in your layout.
- Detect when the content is scrolling. We can do this by adding a listener to the views. In a RecyclerView we use addOnScrollListener. And in NestedScrollView we use setOnScrollChangeListener.
- Animate the elevation visibility. There is no elevation property in ViewCompat API to animate. We need to use translationZ.
- Don’t forget to set the started toolbar elevation to 0dp.
So grouping everything together we end up with:
For RecyclerView:
The result will be something like this:
If you don’t want to implement all the logic yourself, I develop a lib that has a custom toolbar with this feature built-in. Feel free to check it out:
Extra Goodies
Since this is all about toolbars, here is how to implement the other visible changes:
Center Title
To center the title in a toolbar you need to add a view to it. In this case a TextView. And change its layout gravity to center. Here is an example:
New font
To use a font similar to google apps, change the font family to sans-serif. Like this: