https://kotlinlang.org logo
Title
l

louiscad

08/23/2019, 10:07 AM
For Views DSL users: Would you use such an overload of the
add
extension for
ViewGroup
?
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
:yes: 1
r

ribesg

08/23/2019, 11:05 AM
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

louiscad

08/23/2019, 1:13 PM
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

ribesg

08/23/2019, 1:29 PM
Maybe have two functions
addBefore
and
addAfter
then. XOR parameters are not obvious to use
l

louiscad

08/23/2019, 3:28 PM
But then, there's a repetition with the parameter names
i

ispbox

08/24/2019, 5:32 PM
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

louiscad

08/25/2019, 12:28 AM
🤔
Found a solution:
@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) }
}