I want to create a custom contentScrim for my collapsingToolbarLayout
. My collapsingToolbarLayout has an imageview
inside. When it scrolls, in theory t
This is how I managed to create a custom scrim, which seems to be used in quite a few apps nowadays - if you look at Facebook, you will see they do not use the standard contentScrim
for their collapsingToolbarLayout
. The code below duplicates what Facebook does in their app.
You must set a AppBarLayout.OnOffsetChangedListener
to your activity and then use the following code below to measure the size of the toolbar and the size of the appBarLayout.
When your listener is called, the verticalOffset
actually measures the offset of the collapsingToolbarLayout
from when it is fully expanded to the point when it touches the pinned toolbar
. Therefore, the verticalOffset
EXCLUDES the height of the toolbar
. To compare apples with apples, we need to also EXCLUDE the toolbar
height from the height of the appBarLayout
so that when we divide the verticalOffset
by the totalHeight
, neither the verticalOffset nor the totalHeight contains the toolbar
height. This is necessary in order to obtain a percentage to apply your 255 alpha value to.
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
//measuring for alpha
int toolBarHeight = toolbar.getMeasuredHeight();
int appBarHeight = appBarLayout.getMeasuredHeight();
Float f = ((((float) appBarHeight - toolBarHeight) + verticalOffset) / ( (float) appBarHeight - toolBarHeight)) * 255;
fading_backdrop.getBackground().setAlpha(255 - Math.round(f));
}
When you scroll now, the fading_backdrop
will gradually gain alpha when you scroll upwards so that it overlays nicely with the image in the collapsingToolbarLayout
, similar to the facebook custom contentScrim
.