1

I'm trying to scroll a ScrollView in a loop and do something between the scrolls until it reaches the bottom. Ideally, I would like to scroll it "page-by-page" to minimize the number of scrollBy invocations and to avoid showing the same content twice.

I tried something like this:

var afterScrollY: Int

val scrollBy = scrollView.height

do {
    val beforeScrollY = scrollView.scrollY

    // This is why I need to scroll "page-by-page" instead of going straight to the bottom
    doSomethingAtCurrentScrollPosition()

    scrollView.scrollBy(0, scrollBy)
    afterScrollY = scrollView.scrollY
} while (afterScrollY != beforeScrollY)

but it looks like scrolling by the ScrollView's height doesn't do exactly what I want.

Expected and actual behavior

My layout is very simple and doesn't contain any margins or paddings:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:fillViewport="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:id="@+id/frame"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:gravity="center"
            android:orientation="vertical" />

    </ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
2
  • Not sure if you aware of developer.android.com/reference/androidx/recyclerview/widget/… Commented Mar 9, 2023 at 21:04
  • Thanks @MorrisonChang but don't want to snap the ScrollView's position to the views inside it. I thought maybe there is a better property than height to find the right number of pixels to scroll by. For context: my goal is to take a screenshot of the whole ScrollView's content. Commented Mar 10, 2023 at 10:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.