ScrollView

时间:2018-05-27 09:49:21

标签: java android

我在垂直滚动TextView的同时尝试淡入和淡出ScrollView。每当我慢慢滚动时,我都会正确地使它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;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果您需要在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);
            }
        }
    });