0

I created a CardView widget, inside of which a TextView is. The text of the TextView changes in the runtime. How can I bind my CardView width to the TextView width?

What I have tried so far:

In the CardView, I added, android:layout_alignLeft="@id/textViewUser" but it doesn't work as the TextView can't be nested using this method. Any idea?

A snippet of the CardView item is the following. Please note I removed the constraints to make it shorter.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardViewUser"
        android:layout_width="300dp"
        android:layout_height="30dp"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="10dp"
        android:layout_marginBottom="10dp"
        card_view:cardCornerRadius="4dp"
        card_view:elevation="14dp">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginBottom="8dp"
                android:text="I change during runtime"
                android:id="@+id/textViewUser"/>
        </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.cardview.widget.CardView>
</RelativeLayout>
Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
Alan
  • 589
  • 5
  • 29

1 Answers1

3

If I understand you correctly you want to keep width of the CardView connected with the TextView. You can try something like this:

<androidx.cardview.widget.CardView
    android:id="@+id/cardViewUser"
    android:layout_width="wrap_content"
    android:layout_height="30dp"
    android:layout_marginStart="10dp"
    android:layout_marginTop="10dp"
    android:layout_marginEnd="10dp"
    android:layout_marginBottom="10dp"
    card_view:cardCornerRadius="4dp"
    card_view:elevation="14dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="8dp"
            android:text="I change during runtime"
            android:id="@+id/textViewUser"/>

</androidx.cardview.widget.CardView>
blackr4y
  • 260
  • 5
  • 10