Doubidou
Doubidou

Reputation: 1791

Android, constraintLayout with constraintDimensionRatio that fit in screen (or another constraintLayout)

I was happily coding a constraintLayout with a constraintDimensionRatio 1:1, that gives me a centered square with some padding.

<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="match_parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/board"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="32dp"
        android:layout_marginEnd="32dp"
        android:background="@color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

BUT, for my usecase, I had to dynamically change the ratio ; so I tried a 10:1, and I discover that my view is always vertically centered and with some padding, but overflows the screen with its height :(

Is there a way to have a fully-centered view, that works with any constraintRatio, that could be kept in its parent layout and exploiting all available space in this one ?

Thanks !

Upvotes: 0

Views: 205

Answers (1)

Luiz Fernando de Moura
Luiz Fernando de Moura

Reputation: 216

I don't know if I fully understood, but if you want keep the ratio 10:1 but keep the view inside the parent, just change both layout_height and android:layout_width to 0dp, like so:

<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="match_parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/board"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="32dp"
        android:layout_marginEnd="32dp"
        android:background="@color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="1:10"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Upvotes: 2

Related Questions