S. Sargsyan
S. Sargsyan

Reputation: 53

Fill remaining space with a view that has aspect ratio in ConstraintLayout

I have two views (viewA, viewB) in vertical chain. aspect ratio of viewA should always be 1:1, while height of viewB is dynamic (it may be 400dp, may be 700dp)

Expected results: Width viewA should be reduced (keeping the aspect ratio) when the height of viewB is too big to fit two views in screen.

Actual result: Width of viewA always matches parent and views leave bounds of screen if height of viewB is too big.

NOTE: It is desired to use ConstantsLayout and don't have nested viewgroups.

<View
    android:id="@+id/viewA"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/viewB"
    app:layout_constraintDimensionRatio="h,1:1"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_chainStyle="spread"/>

<View
    android:id="@+id/viewB"
    android:layout_width="match_parent"
    android:layout_height="700dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/viewA"/>

Upvotes: 4

Views: 1004

Answers (1)

Cheticamp
Cheticamp

Reputation: 62851

Change the dimension ratio of the top view to the following:

app:layout_constraintDimensionRatio="w,1:1"

Now, when the bottom view height changes, the top will track as you want while maintaining the 1:1 ratio. I added color to better see the views in the layout.

Bottom view at 700dp

enter image description here

Bottom view at 500dp

enter image description here

Bottom view at 200dp

enter image description here

Upvotes: 4

Related Questions