Francois Morvillier

    Francois Morvillier

    1 year ago
    I find that many of the custom components I want to write rely on being able to access the layout positions of child views. Typically, I'll want to select a certain child view (highlight it and make a callback) depending on how much the view was scrolled (for instance selecting the middle child in a carousel selector assuming varying child sizes). I have been able to solve this by writing a custom layout that saves the child positions to a remembered value but it feels like too much work and ideally I'd like to be able to use any existing layout without having to redo it. Is there a better way to access the child layout positions?
    k

    Kirill Grouchnikov

    1 year ago
    Where do you want to access that information from? From inside the parent measure pass, or somewhere else?
    Francois Morvillier

    Francois Morvillier

    1 year ago
    Here's a simplified version of how I'd like to write it:
    val scrollState = rememberScrollState()
    val selectedIndex = // compute the selected child index using scrollState.value and child layout info
    Row(modifier = Modifier.horizontalScroll(scrollState)) {
        // children declarations
        for(i in 1..N) {
             Child(i, selectedIndex)
        }
    }
    The question is how to I get the layout positions of the children so I can compute selectedIndex?
    k

    Kirill Grouchnikov

    1 year ago
    Maybe in this particular case, you don't need the positions of all the child views. If you need to set the selected index based on which child is in the middle, that can be a
    State
    variable at the parent level which is updated in your measure pass.
    It's a bit of a perspective shift to not look at the layout information for this
    Francois Morvillier

    Francois Morvillier

    1 year ago
    So basically it does require a custom layout? In that case it may indeed be smarter to compute the selected index in the layout measure pass.