Android Set ConstraintLayout Dimension Ratio Programatically

Initialize by code

(imageView.layoutParams as ConstraintLayout.LayoutParams).dimensionRatio = "H,2:1"

Change dimention ratio at runtime dynamically

imageView.updateLayoutParams<ConstraintLayout.LayoutParams> {    dimensionRatio = "H,2:1"}

NOTE: The above using android-ktx

or

val layoutParams = imageView.layoutParams as ConstraintLayout.LayoutParamslayoutParams.dimensionRatio = "H,2:1"imageView.layoutParams = layoutParams

XML

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:scaleType="centerCrop"
        app:layout_constraintDimensionRatio="H,2:1"
        />

</android.support.constraint.ConstraintLayout>

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.