簡體   English   中英

ScrollView中的淡入/淡出視圖

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM