Search code examples
androidandroid-layoutandroid-scrollview

Sticking a view to bottom of scrollview


I have a weird behavior I cant figure out - I'm trying to stick a view to bottom of scrollview with no luck. I've already tried clipToPadding and fillViewport but none of them help. Any help? My xml layout is -

<LinearLayout>

    <FrameLayout/>
    <ScrollView>
        <LinearLayout>
            <LinearLayout/>
            <RelativeLayout/> <-- This is the problematic view
        </LinearLayout>
    </ScrollView>

</LinearLayout>

I want to stick the relative layout to bottom even when the scroll view is shorter then the screen length, it does fit the screen when clipToPadding is set to false however the relativelayout just laid in middle of screen after the linearlayout which ontop of him, when I set the fillviewport to true on the scrollview (and remove the cliptopadding) the scrollview is longer than screen but unscrollable which lead to the relativelayout being "invisible", any suggestions?


Solution

  • You can try using ConstraintLayout inside ScrollView:

    1. Set fillviewport in ScrollView to True
    2. Last element must be attached on the bottom with constraints
    3. Last but one element (one who goes before last) should have constraint set to last element. Also you can add margin to have minimum distance between this and last element and manage its position with constraintVertical_bias.

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">
    
    <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
        … Some elements with Constraints …
    
        <TextView
                android:id="@+id/last_but_one_element”
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"                        
                app:layout_constraintBottom_toTopOf="@+id/some_previous_element"
                app:layout_constraintTop_toBottomOf="@+id/last_element"
                android:layout_marginBottom=“40dp"
                app:layout_constraintVertical_bias="0.1"/>
    
        <Button
                android:id="@+id/last_element”
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"/>
    
    </androidx.constraintlayout.widget.ConstraintLayout>