Created
June 3, 2020 12:52
-
-
Save sbelloz/a925b0da3bc4eb893b9df1a1ae4d290b to your computer and use it in GitHub Desktop.
SingleLineLinearLayout
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 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