How to create constraints programmatically with ConstraintLayout in Android

Issue #381

From API < 17, there is ViewCompat.generateViewId()
For API 17, there is View.generateViewId()

Note that to use ConstraintSet, all views under ConstraintLayout inside xml must have unique id

1
2
3
4
5
6
7
8
9
val imageView = ImageView(context)
imageView.id = View.generateViewId()
imageView.setImageResource(resId)
constraintLayout.addView(imageView)

val set = ConstraintSet()
set.clone(constraintLayout)
set.connect(imageView.id, ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT)
set.applyTo(constraintLayout)

Comments