Skip to content

Instantly share code, notes, and snippets.

@sbelloz
Created June 3, 2020 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbelloz/a925b0da3bc4eb893b9df1a1ae4d290b to your computer and use it in GitHub Desktop.
Save sbelloz/a925b0da3bc4eb893b9df1a1ae4d290b to your computer and use it in GitHub Desktop.
SingleLineLinearLayout
/**
* Class describing a SingleLineLinearLayout
*/
open class SingleLineLinearLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
var isChildRemoving = false
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (!isChildRemoving) {
// measure all children and get sum width
var childWidthOccupied = children.sumBy {
it.measure(widthMeasureSpec, heightMeasureSpec)
it.measuredWidth + it.marginEnd
}
val parentWidth = measuredWidth
if (childWidthOccupied > parentWidth) {
isChildRemoving = true
for (i in childCount - 1 downTo 0) {
val child = get(i)
val childWidthWithMargin = child.measuredWidth + child.marginEnd
if (childWidthOccupied <= parentWidth) {
isChildRemoving = false
break
}
childWidthOccupied -= childWidthWithMargin
removeViewAt(i)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment