I'm trying to fade in and out a TextView
while scrolling a ScrollView
vertically. Whenever I scroll slowly, I'm getting it right making the TextView
invisible as it faded out. The problem is, when I scroll faster, it is not completely gone. Here is my code:
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (t > oldt) {
float newAlpha = alpha - 0.02f;
if (newAlpha >= 0.0f) {
for (View view : fadingViews) {
view.setAlpha(newAlpha);
alpha = newAlpha;
}
}
} else {
float newAlpha = alpha + 0.02f;
if (newAlpha <= 1.0f) {
for (View view : fadingViews) {
view.setAlpha(newAlpha);
alpha = newAlpha;
}
}
}
}
If you need to have a fading edge in your ScrollView
, you might consider adding some like the following in your layout xml of ScrollView
.
<ScrollView android:requiresFadingEdge="vertical">
However, I am thinking you are looking for something like the following to set alpha in your views programatically.
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 + (view.getHeight() / 2);
// scroll is up past the variance, so start to show it
if (scrollDisparity > 0 && scrollDisparity < mScrollVariance) {
newAlpha = scrollDisparity / mScrollVariance;
view.setAlpha(newAlpha);
// scroll is below the variance so start to hide it
} else if (scrollDisparity >= -mScrollVariance && scrollDisparity < 0) {
newAlpha = scrollDisparity / mScrollVariance;
view.setAlpha(newAlpha);
// just in case the user swipes too fast, these are the fallbacks
} else if (scrollDisparity > mScrollVariance) {
view.setAlpha(1);
} else if (scrollDisparity < -mScrollVariance) {
view.setAlpha(0);
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.