user11755923
user11755923

Reputation:

Change the background color on scroll

I have a scroll view and when the user scrolls it I want to change the background color slowly and gradually. How can I achieve the following ?

Upvotes: 3

Views: 691

Answers (2)

Caio Mar
Caio Mar

Reputation: 2624

Similarly to the accepted answer, this is how I did it in 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
            )
        }
    }
}

Upvotes: 0

PPartisan
PPartisan

Reputation: 8231

Use a NestedScrollView and attach an OnScrollChangeListener. Then combine it with an ARGBEvaluator to generate a colour, and set that you your background. I'm going from memory, but something like:

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);
});

Upvotes: 2

Related Questions