Y’s Lazy Guide: ConstraintLayout in Android Studio (Code Edition)

Irfan Yas
3 min readApr 10, 2020

Mostly used attributes when I code ConstraintLayout:

android:id = “@+id/whatever_you_want”

For the illustration below:

  • Blue Circle => android:id = “@+id/circle”
  • Red Square => android:id = “@+id/square”

android:layout_width and android:layout_height = “match_parent | wrap_content | 0dp”

  • match_parent => exact same size as the screen
  • wrap_content => default size of the view
  • 0dp => relative, use with constraint
illustration for android:layout_width and android:layout_height

app:layout_constraintX_toYOf = “parent | @id/other_view

  • change X and Y to => Start / End / Top / Bottom
  • parent => relative position with the upper level of this view
  • @id/other_view => relative position with the other_view
app:layout_constraintX_toYOf with blue text for blue square view and red text for red square view

app:layout_constraintHorizontal_bias and app:layout_constraintVertical_bias = “0 .. 1”

  • Vertical 0 => the most top position this view can reach
  • Vertical 1 => the most bottom position this view can reach
  • Horizontal 0 => the most start position this view can reach
  • Horizontal 1 => the most end position this view can reach
app:layout_constraintHorizontal_bias and app:layout_constraintVertical_bias

app:layout_constraintWidth_percent and app:layout_constraintHeight_percent = “0 .. 1”

  • Width 0 => 0% width view from width screen
  • Width 1 => 100% width view from width screen
  • Height 0 => 0% height view from height screen
  • Height 1 =>100% height view from height screen
  • NOTE: If the value is “1”, it will stop when hit a constraint. If the value is between 0 until 1, it will change it’s relative to screen size.
app:layout_constraintWidth_percent and app:layout_constraintHeight_percent

Honorable mentions

  • app:layout_constraintHorizontal_chainStyle and app:layout_constraintVertical_chainStyle = “packed | spread | spread_inside”
  • app:layout_constraintDimensionRatio = “H|W, ratio”. Change ratio to whatever needed like 1:1, 3:4, 16:9
Truth is I don’t really understand how these attributes work. Just experiment with it until you get what you want.

Example in Project

XML code below
Example using ConstraintLayout (not necessarily the best practice in a real project)

Please leave a comment or contact me in case I put a wrong code or explanation. If you more of a palette person, you can learn about ConstraintLayout in https://developer.android.com/training/constraint-layout. Hope this article makes your coding session more enjoyable and have a good day :)

--

--