Skip to content

Instantly share code, notes, and snippets.

@bkurzius
Created April 17, 2015 21:16
Show Gist options
  • Save bkurzius/a4d165683a57742ad4c9 to your computer and use it in GitHub Desktop.
Save bkurzius/a4d165683a57742ad4c9 to your computer and use it in GitHub Desktop.
Android ScrollView -- fade a view in or out depending on the vertical scroll postion
mScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
// the scrollposition that the fade will start
int mScrollThreshold = 100;
// how fast the view will fade with the scroll -- use multiples of 10
int mScrollVariance = 40;
int scrollY = mScrollView.getScrollY();
// if the difference between the scrollthreshold is +/-mScrollVariance, show the view accordingly
float newAlpha = 0;
float scrollDisparity = scrollY - mScrollThreshold + (mToolbarSeriesTitle.getHeight()/2);
// scroll is up past the variance, so start to show it
if(scrollDisparity > 0 && scrollDisparity < mScrollVariance) {
newAlpha = scrollDisparity / mScrollVariance;
mToolbarSeriesTitle.setAlpha(newAlpha);
// scroll is below the variance so start to hide it
}else if (scrollDisparity >= -mScrollVariance && scrollDisparity < 0) {
newAlpha = scrollDisparity / mScrollVariance;
mToolbarSeriesTitle.setAlpha(newAlpha);
// just in case the user swipes too fast, these are the fallbacks
}else if(scrollDisparity > mScrollVariance){
mToolbarSeriesTitle.setAlpha(1);
}else if(scrollDisparity < -mScrollVariance){
mToolbarSeriesTitle.setAlpha(0);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment