Android View Collisions

How to try to prevent view intersection

Base Solution

OnMeasure

override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
val fixedL = l + paddingLeft
val fixedT = t + paddingTop
val fixedR = r - paddingRight
val fixedB = b - paddingBottom

when(childCount) {
1 -> layoutOneChild(fixedL, fixedT, fixedR, fixedB)
2 -> layoutTwoChildren(fixedL, fixedT, fixedR, fixedB)
else -> layoutTreeChildren(fixedL, fixedT, fixedR, fixedB)
}
}
Animation of collapsing and expanding layout with 1, 2 and 3 children to see, how view deform their positions

👍Boost 1️⃣: Extrapolate it for any child count

Di is an distance between center of View_i element and View_(i + 1) element, except View1 (top) and View4 (bottom).

Concept of algorithm

weight[i] = (view[i].height + view[i + 1].height) / 2
weight[0] = view[0].height + view[1].height / 2
weight[n - 2] = view[n - 2].height / 2 + view[n - 1].height
totalHeight = children.sum { it.height }
The freeHeight from the top is distributed between all elements of sortedWeights

Implementation

Results

👍Boost 2️⃣: Add offsets

left: we can do that, right: we can not do that yet

Concept

Implementation

private class Bucket(
val filled: Float,
val scales: Float,
val position: Int
)

Results

Afterwords

Love being creative to solve some problems with an simple and elegant ways