Search code examples
androidandroid-scrollview

Scrolling with ScrollView not working after adding views programmatically to hierarchy


I´m adding programmatically Views to a LinearLayout, that is embedded in a ScrollView. The ScrollView however does not take into account that extended height, so scrolling won´t work. Calling invalidate() and requestLayout() on the ScrollView after adding the Views did not solve the problem. How it has to be done?

<ScrollView
    android:id="@+id/scrollView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:fillViewport="true"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/pager">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp">

        <LinearLayout
            android:id="@+id/layout_to_which_views_are_added"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/label"> 


services.groupBy { it.category }.forEach { category ->
                val view = layoutInflater.inflate(R.layout.service_category, rootLayout, false)
                view.findViewById<TextView>(R.id.lblHeader).text = getStringArray(R.array.service_category_headers)[category.key]
                view.findViewById<TextView>(R.id.txtServices).text = category.value.joinToString(", ") { it.display }
                layout_to_which_views_are_added.addView(view)
            }
scrollView.invalidate()
scrollView.requestLayout()

Solution

  • Found the problem, the parenting layout of the ScrollView, a CoordinatorLayout, itself being parented by a ConstraintLayout, was missing the bottomToBottom-to-parent constraint, which would stretch it to the bottom, which then makes the ScrollView scrollable to whole content