Search code examples
androidandroid-layoutandroid-scrollview

How to make an item in a ScrollView be positioned in the center of the screen


I have three CardView in a HorizontalScrollView and I want the middle one to be in the center of the screen (as if the user had swiped to get to it). How do I do that in XML or programmatically?

XML layout:

<HorizontalScrollView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="16dp"
    android:scrollbars="none"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/culture_toolbar">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <androidx.cardview.widget.CardView
            android:id="@+id/one"
            android:layout_width="300dp"
            android:layout_height="300dp"
            android:layout_marginEnd="10dp"
            app:cardCornerRadius="12dp">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:src="@drawable/beach_bg_placeholder" />

        </androidx.cardview.widget.CardView>

        <androidx.cardview.widget.CardView
            android:id="@+id/two"
            android:layout_width="300dp"
            android:layout_height="300dp"
            app:cardCornerRadius="12dp">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:src="@drawable/beach_bg_placeholder" />

        </androidx.cardview.widget.CardView>

        <androidx.cardview.widget.CardView
            android:id="@+id/three"
            android:layout_width="300dp"
            android:layout_height="300dp"
            app:cardCornerRadius="12dp">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:src="@drawable/beach_bg_placeholder" />

        </androidx.cardview.widget.CardView>
    </LinearLayout>
</HorizontalScrollView>

This is the result I'm going for:

I want the upper half the mockup


Solution

  • How do i do that in xml preferably?

    AFAIK using XML only that is not possible

    How to make an item in a ScrollView be positioned in the center of the screen

    I would suggest that you should use carousel layout instead of using HorizontalScrollView

    You can make carousel layout using ViewPager and using RecyclerView

    Check out below good articles for carousel layout