I want to change the alpha of toolbar base on scroll, like below:
At first, the toolbar is transparent and by scrolling to the bottom it will more and more visible and at the end it will be fully opaque (visible).
The structure of my layout is:
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="@+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_collapseMode="parallax">
....
</RelativeLayout>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:id="@+id/scroll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
....
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
Content of nested scrollview will be change dynamically from server so I don't know it's height.
I just found 2 ways to detect scrollY:
addOnScrollChangedListener:
scroll.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { // use scroll.getScrollY() } });
setOnScrollChangeListener:
scroller.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() { @Override public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { } });
But none of these ways are not smooth. for example if you check the value of scrollY
(by using log.d()
) you will see something like:
scrollY: 58
scrollY: 117
scrollY: 167
scrollY: 192
scrollY: 195
scrollY: 238
scrollY: 281
scrollY: 338
There is a large gap between numbers.
My question is: How to get percentage of scroll every moment (smoothly)? Or any other way to change alpha of toolbar base on current position of scroll?