Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A function to programmatically add views to ConstraintLayout with Flow
class ChipsView<T : Parcelable>(ctx: Context, attr: AttributeSet) : ConstraintLayout(ctx, attr) {
...
private fun addSubviews() {
val flow = Flow(context).apply {
id = generateViewId()
setWrapMode(Flow.WRAP_CHAIN)
setHorizontalStyle(Flow.CHAIN_PACKED)
setHorizontalAlign(Flow.HORIZONTAL_ALIGN_START)
setHorizontalBias(0f)
setVerticalGap(pillMarginWidth)
setHorizontalGap(pillMarginWidth)
setOrientation(Flow.HORIZONTAL)
layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
}
val constraintSet = ConstraintSet().apply {
clone(this@ChipsView)
clear(flow.id, ConstraintSet.END)
clear(flow.id, ConstraintSet.START)
clear(flow.id, ConstraintSet.BOTTOM)
connect(flow.id, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START)
connect(flow.id, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END)
connect(flow.id, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM)
}
constraintSet.applyTo(this)
addView(flow)
val referenceIds = IntArray(pills.size)
loop@ for ((index, pill) in pills.withIndex()) {
val textView = pill.asTextView()
referenceIds[index] = textView.id
addView(textView)
}
flow.referencedIds = referenceIds
post { requestLayout() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment