Home > Enterprise >  Add Constraints to ConstraintLayout - Android Studio
Add Constraints to ConstraintLayout - Android Studio

Time:07-14

I've been trying to use constraints with a ConstraintLayout with an ID of card_details to position it on the screen, but the constraints are not working, and the IDE is not recommending them as available attributes as well.

Here's the code I'm using.

<com.google.android.material.card.MaterialCardView
    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:id="@ id/product_card"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="15dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <ImageView
        android:id="@ id/product_image"
        android:layout_width="match_parent"
        android:layout_height="280dp"
        android:scaleType="centerCrop"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="ImageContrastCheck"
        tools:srcCompat="@tools:sample/backgrounds/scenic" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@ id/card_details"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="15dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="15dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/product_image">

        <TextView
            android:id="@ id/product_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@ id/product_price"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/product_title" />
    </androidx.constraintlayout.widget.ConstraintLayout>

</com.google.android.material.card.MaterialCardView>

Here's how they look like: How the constraints look

The highlighted item should be placed beneath the image with these constraints, but they don't for some reason.

app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/product_image"

Any idea why? Help is appreciated. Thanks.

CodePudding user response:

Because the ImageView is not inside the ConstraintLayout. You can only put constraints with respect to other views inside that ConstraintLayout. Try moving the ImageView inside the ConstraintLayout

  • Related