-
-
Save dmitrykolesnikovich/7f2404f2e4c68acc29fd713666c7fce5 to your computer and use it in GitHub Desktop.
A function to programmatically add views to ConstraintLayout with Flow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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