Search code examples
javaandroidxmlscrollviewandroid-linearlayout

Android : LinearLayout with weight inside a ScrollView


I'm having this frustrating issue with my ScrollView, here is my hierarchy :

ScrollView (Vertical)
    LinearLayout (Vertical)
        ImageView weight= 0.5
        Whatever weight= 0.1
        Whatever weight= 0.2
        Whatever weight= 0.2

If I remove the ScrollView (and let the LinearLayout as main item), this work properly with any Image : The image takes 50% of the screen size, and the other Views take fill the rest.

However, when the ScrollView is here, the "weight" parameter is completely ignored if my Image is too tall : The image will do anything it can to fit the screen width, and then will be obviously too tall and take more than 50% of the screen. EDIT : actually, all the "weight" attributes seem ignored :

Without ScrollView: enter image description here

With ScrollView: enter image description here

I want the Linear Layout to fit perfectly without having to Scrolling. Is that possible ? I've tried to change some of the image option (scaleType, adjustViewBounds) but I didn't manage to have what I wanted.

Here's the whole xml :

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1">


    <ImageView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.5"
        android:adjustViewBounds="true"
        android:src="@drawable/testing" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.2"
        android:text="I'M A TEST" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.1"
        android:text="I'M A TEST" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.2"
        android:text="I'M A TEST" />

</LinearLayout>
</ScrollView>

Note : I need the ScrollView because I'm using a PullToRefresh ScrollView


Solution

  • I solved it by adding a parent Linear Layout (and a main relativeLayout) :

        ScrollView (Vertical)
            LineaLayout
                LinearLayout (Vertical)
                    ImageView weight= 0.5
                    Whatever weight= 0.1
                    Whatever weight= 0.2
                    Whatever weight= 0.2
    

    And setting programmatically the height of the child LinearLayout to the height of the screen with childLinearLayout.getLayoutParams().height