Search code examples
javaandroidscrollviewchildren

Scrollview - How do you make a scroll view display 2 children at a time yet still relative to the screen size?


I'm wondering if there is any way to make the children inside a ScrollView only show 2 children at a time. I have tried making the layout heights of each children = 0dp and setting the weight but it displays all the children at once. I have tried setting the children heights to a specific amount and it works but only for my certain screen size.

Here is my sample code :

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

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

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#ff0000"
        android:layout_weight=".5"></LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#7458ff"
        android:layout_weight=".5"></LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#56ffe3"
        android:layout_weight=".5"></LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#ffffff"
        android:layout_weight=".5"></LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#fffd69"
        android:layout_weight=".5"></LinearLayout>
</LinearLayout>

Here is what it looks like when I set the view height to 0dp and use weights

But I only want it to display 2 at a time


Solution

  • One sollution is to set height of each child programmaticaly like

    view.getLayoutParams().height = getHalfScreenSize();
    

    And the half screen size like this:

      DisplayMetrics metrics = new DisplayMetrics();
      getWindowManager().getDefaultDisplay().getMetrics(metrics).heightPixels/2;