Search code examples
androidandroid-linearlayout

Why we need LinearLayout inside of CardView?


I have following xml code from youtube:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity">

    <androidx.cardview.widget.CardView
        android:layout_width="300dp"
        android:layout_height="300dp"
        app:cardElevation="10dp"
        app:cardCornerRadius="20dp"
        app:cardBackgroundColor="@color/white"
        tools:ignore="MissingConstraints">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <ImageView
                android:layout_height="150dp"
                android:layout_width="match_parent"
                android:src="@drawable/sandwich"
                android:id="@+id/sandwich"
                android:scaleType="centerCrop"
                tools:ignore="MissingConstraints" />
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="match_parent"
                android:text="Welcome"
                android:textAlignment="center" />
        </LinearLayout>

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

Why we need the LinearLayout that inside the Card component? Can we just inside the Card use ImageView and Text component alone.


Solution

  • CardView is basically a styled FrameLayout source code, thus it doesn't support placing multiple views inside it, unless you want to stack them on each other. So to get around that, you can place a layout that supports multiple views and use it to manage the placement. It doesn't have to be LinearLayout, you can use any available Layout out there.