java 更改滚动时的背景色

siv3szwd  于 2022-12-17  发布在  Java
关注(0)|答案(2)|浏览(130)

我有一个滚动视图,当用户滚动它时,我想慢慢地逐渐改变背景颜色。我如何实现以下操作?

tjrkku2a

tjrkku2a1#

使用一个NestedScrollView并附加一个OnScrollChangeListener。然后将其与一个ARGBEvaluator组合生成一种颜色,并将其设置为背景。我将根据记忆进行操作,但类似于:

final ArgbEvaluator evaluator = new ArgbEvaluator();
final colorStart = Color.GREEN;
final colorEnd = Color.BLUE;
nestedScrollView.setOnScrollChangedListener((view, scrollX, scrollY, oldX, oldY) -> {
    final float height = (float) v.getHeight();
    if(height <= 0) return;

    final float progress = (float)((float)scrollY/v.getHeight());
    background.setBackgroundColour((int)evaluator.evaluate(progress, startColor, endColor);
});
7bsow1i6

7bsow1i62#

与公认的答案相似,我在Kotlin的回答是这样的:

@RequiresApi(Build.VERSION_CODES.M)
@SuppressLint("RestrictedApi")
private fun setBackgroundAnimation(nestedScrollView: NestedScrollView) {

    val evaluator = ArgbEvaluator()

    val colorStart = context?.getColor(R.color.backgroundColor)
    val colorEnd = Color.BLACK

    var progress: Float
    val velocity = 3

    nestedScrollView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
        val scrollViewHeight = nestedScrollView.height

        if (scrollViewHeight > 0) {
            progress = (scrollY / scrollViewHeight.toFloat()) * velocity
            nestedScrollView.setBackgroundColor(
                evaluator.evaluate(
                    progress,
                    colorStart,
                    colorEnd
                ) as Int
            )
        }
    }
}

相关问题