For Views DSL users: Would you use such an overloa...
# splitties
l
For Views DSL users: Would you use such an overload of the
add
extension for
ViewGroup
?
Copy code
inline fun <V : View> ViewGroup.add(
    view: V,
    lp: ViewGroup.LayoutParams,
    beforeChild: View? = null,
    afterChild: View? = null
): V
If not, would it annoy you to see it in autocomplete? (😤 reaction is fine for that)
👌 1
😤 1
r
I just add the views in the right order in the first place, but it’s good to have options. I suppose it would check if the provided view are in the layout and some cases (like what if afterChild is after beforeChild). And what if there are 9001 views between afterChild and beforeChild?
l
Oh, it might not be obvious from the signature, but it's a XOR. It also checks the before or after view is indeed a child.
Would be helpful for z-ordering without elevation or below API 21, and also when adding views dynamically.
r
Maybe have two functions
addBefore
and
addAfter
then. XOR parameters are not obvious to use
l
But then, there's a repetition with the parameter names
i
I would vote for addBefore/addAfter syntax. But as for me it looks like not very useful feature as the same could be achieved just by container views.
l
🤔
Found a solution:
Copy code
@Suppress("CONFLICTING_OVERLOADS")
@JvmName("addBefore")
inline fun <V : View> ViewGroup.add(
    view: V,
    lp: ViewGroup.LayoutParams,
    beforeChild: View
): V {
    val index = indexOfChild(beforeChild).also {
        check(it != -1) { "Value passed in beforeChild is not a child of the ViewGroup!" }
    }
    return view.also { addView(it, index, lp) }
}

@Suppress("CONFLICTING_OVERLOADS")
@JvmName("addAfter")
inline fun <V : View> ViewGroup.add(
    view: V,
    lp: ViewGroup.LayoutParams,
    afterChild: View
): V {
    val index = indexOfChild(afterChild).also {
        check(it != -1) { "Value passed in beforeChild is not a child of the ViewGroup!" }
    } + 1
    return view.also { addView(it, index, lp) }
}