Search code examples
androidandroid-cardview

How to adjust cardView according to imageView inside in android?


I want my cardView to adjust it self according width and heigh of imageView inside it and achieve effect like this.

enter image description here

enter image description here

But i am not really experienced with designing so i am having trouble. This is the code i am using

<androidx.constraintlayout.widget.ConstraintLayout 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="wrap_content"
    android:layout_marginTop="16dp">

    <TextView
        android:id="@+id/imageTimeMessageSent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="9:16 AM"
        android:textSize="14sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/cardView4"
        app:layout_constraintHorizontal_bias="0.7"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.98" />

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView4"
        android:layout_width="230dp"
        android:layout_height="230dp"
        android:layout_marginEnd="12dp"
        app:cardBackgroundColor="?attr/colorPrimary"
        app:cardCornerRadius="6dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0">

        <ImageView
            android:id="@+id/imageMessageSent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="6dp"
            android:scaleType="centerInside"
            android:src="@drawable/ic_launcher_background"
            tools:srcCompat="@drawable/default_profile" />
    </androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>

The code works fine for most images but some images leave space on cardView

enter image description here enter image description here

Note: I also want to have a certain limit so the cardView does not expand beyond that


Solution

  • So in cardView

    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    

    ImageView

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    

    If you add this it will work as you want.