James
James

Reputation: 45

Forcing a view to take at least a percentage of its parent's height

I have a LinearLayout, the direct child of a ScrollView, with two children. The first child can be almost any height (it's an Image), but the second child will have content that is much larger than the height of the viewport. I tried using layout_weight to achieve this, but that only resulted in the image being set to something like 1dp and the second child taking the rest, because the weights are only assigned to the remaining space.

How do I force the image to take up at least 40% of the screen space?

<ScrollView
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical">

            <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="2"
                android:src="@drawable/my_image" />

            <LinearLayout
                android:id="@+id/prediction_container"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:background="@android:color/white"
                android:orientation="vertical"
                android:layout_weight="1">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="[really long text]" />

            </LinearLayout>

    </LinearLayout>

</ScrollView>

Upvotes: 1

Views: 102

Answers (1)

Aurelian Cotuna
Aurelian Cotuna

Reputation: 3081

You're missing android:adjustViewBounds="true" on your ImageView

Change your ImageView code to something like this

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

Upvotes: 1

Related Questions