As there were some bugs in AppbarLayout scrolling behavior, I got the requirement to implement same behavior with scroll view. So here is how we can do it.
Expected Output
Step 1: Not reinventing the wheel
This library is very good as starting point for our final goal, and here you will find detail explanation about how to create this.
Let’s see the basic structure of the this implementation.
- FrameLayout is used for moving children separately.
- ImageView(@id/image) is the image that will be translated with parallax effect.
- View(@id/overlay) is an overlay view.You can see the image is fading in and out. This view overlaps with the image and its opacity is changed by scroll position.
- ObservableScrollView provide vertical scroll value which is used to scroll other views
- LinearLayout holds the actual content.
- View(@id/paddingtop) provide top padding of 240dp so that main content start below header view.
- TextView(@id/main_content) this represent main content below header.
- LinearLayout(@id/titletext_container) holds title text and the animating area
- TextView(@id/titletext) holds title text which will be scaled and translated on top of the action bar, its minimum height is equal to action bar height.
- View(@id/animating_space) This view provides space for title text to animate. its height is (header height - action bar height).
Step 2: Identifying what need to be done
- The toolbar should stick at the top.
- Title text should stick at the top.
- The status bar should be transparent initially and fade in with the primary color.
- Image View should start below the status bar.
Step 3: Toolbar should stick at top
- As Toolbar should be on top of scrolling content, so place it below ObservableScrollView. Also make toolbar transparent initially.
- As we can see title text is overlapping with up icon, this can be corrected by adding left padding of 56dp(toolbar home icon width) to Title text.
- If user scrolled the content more then flexibleRange, change the Toolbar color to primary else keep it transparent.
Step 4: Status bar color change
- From our final output we can see that initially we need to set status bar color as transparent, so in onCreate we can set below code.
But this will result in following output
Basically we need to move image below status bar, this can be done with below code
You can see Toolbar overlapped with status bar, we need to set top padding to toolbar and it should be of status bar height.
But this cause another issue, i.e Toolbar color change will be visible with a flicker as shown below.
This is because we increased action height by adding extra padding but didn’t updated mActionBarSize value so add following
Step 5: Title text should stick at top
- Translate Title text till it reaches status bar height, this will stick TextView at top.
Instead of
Do this
And hear is our final output
You can find the code here
Thanks for reading