How To Get Percentage Of Scroll In Nestedscrollview Any Time (smoothly)?
Solution 1:
You can add an scrollListener to ScrollView
.
The calculation of scrolled percentage of your scrollView:
doublepercent= ((((float) scrollY) / ((float) (scrollContentHeight - screenHeight + statusBarHeight))));
The top edge of the displayed part of your view:
scrollY = scrollView.getScrollY()
The
scrollView
has one child andscrollContentHeight = scrollView.getChildAt(0).getHeight()
is the height of the content of scrollView.We need to calculate the max height of top edge in full scrolled state:
scrollContentHeight - screenHeight + statusBarHeight
Finished!
percent = scrollY*100 / (scrollContentHeight - screenHeight + statusBarHeight)
And set the color:
view.setBackgroundColor(Color.argb((int) (255.0 * (percent/100)), r, g, b));
scrollView.getViewTreeObserver().addOnScrollChangedListener(newViewTreeObserver.OnScrollChangedListener() {
@OverridepublicvoidonScrollChanged() {
intscrollY= scrollView.getScrollY();
intscrollContentHeight= scrollView.getChildAt(0).getHeight();
intscreenHeight= Utility.getScreenHeight(context);
intstatusBarHeight= Utility.getStatusBarHeight(context);
intcolor= getResources().getColor(R.color.colorPrimary);
intr= (color >> 16) & 0xFF;
intg= (color >> 8) & 0xFF;
intb= (color >> 0) & 0xFF;
doublepercent= ((((float) scrollY) / ((float) (scrollContentHeight - screenHeight + statusBarHeight))));
if (percent >= 0 && percent <= 1)
toolbar.setBackgroundColor(Color.argb((int) (255.0 * percent), r, g, b));
}
});
Solution 2:
try this
scrollview.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
publicvoidonScrollChanged() {
double scrollViewHeight = scrollview.getChildAt(0).getBottom() - scrollview.getHeight();
double getScrollY = scrollview.getScrollY();
double scrollPosition = (getScrollY / scrollViewHeight) * 100d;
Log.i("scrollview", "scroll Percent Y: " + (int) scrollPosition);
}
});
it will show the percentage from 0 to 100%
Solution 3:
Try this method:
nestedScrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
int verticalScrollableHeight = v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight();
float verticalPercentage = ((float) scrollY) / verticalScrollableHeight;
Solution 4:
These answers are ignoring the effect of any top or bottom padding on the scroll view, which is effectively extra scroll span, so I found I needed:
valverticalScrollableHeight= firstChild.measuredHeight - scrollView.measuredHeight + scrollView.paddingBottom + scrollView.paddingTop
listener(scrollView.scrollY.toFloat() / verticalScrollableHeight)
Post a Comment for "How To Get Percentage Of Scroll In Nestedscrollview Any Time (smoothly)?"