Elye Elye - 6 months ago 29
Android Question

Should CardView always wrap a layout first?

I have a cardview with only one textview.

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:foreground="@drawable/selector_normal"
android:clickable="true"
card_view:cardCornerRadius="2dp">

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

<TextView
android:id="@+id/txt_command"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="@dimen/padding_standard"
android:padding="@dimen/padding_standard"
android:textColor="@color/colorLightBlue"
android:textSize="@dimen/text_size_medium_small" />

</LinearLayout>
</android.support.v7.widget.CardView>


Apparently the LinearLayout does nothing other than wrapping the TextView. However if I remove the LinearLayout, having the CardView wrap just the TextView, my entire TextView disappear. Is this not allowed?

Is it possible to remove the LinearLayout?

I want to reduce my layout hierarchy by removing redundant layout.

Answer

No, it is not necessary to have LinearLayout above than android.support.v7.widget.CardView

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="1dp"
    android:clickable="true"
    android:foreground="@drawable/selector_normal"
    card_view:cardCornerRadius="2dp">

    <TextView
        android:id="@+id/txt_command"
        android:layout_width="match_parent" //change here to match_parent
        android:layout_height="wrap_content"
        android:drawablePadding="@dimen/padding_standard"
        android:padding="@dimen/padding_standard"
        android:textColor="@color/colorLightBlue"
        android:hint="Your Text Here"
        android:textSize="@dimen/text_size_medium_small"/>

</android.support.v7.widget.CardView>