[英]Fading in/out view in ScrollView
我试图在垂直滚动ScrollView
时淡入和淡出TextView
。 每当我缓慢滚动时,我都会正确地使TextView
淡出时不可见。 问题是,当我滚动得更快时,它并没有完全消失。 这是我的代码:
@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;
}
}
}
}
如果您需要在ScrollView
使用渐变色,则可以考虑在ScrollView
的布局xml中添加如下所示的内容。
<ScrollView android:requiresFadingEdge="vertical">
但是,我认为您正在寻找类似以下内容的内容,以便以编程方式在视图中设置Alpha。
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);
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.