Android | Get all children elements of a ViewGroup

后端 未结 7 1609
星月不相逢
星月不相逢 2020-12-08 02:56

getChildAt(i) on gets only the direct children of a ViewGroup, is it possible to access to all children without doing nested loops?

7条回答
  •  旧巷少年郎
    2020-12-08 02:58

    For those using androidx and kotlin

    1 - Iterate through ViewGroup using forEach{}

    If you want to iterate through all childViews, you can use predefined kotlin extension forEach in any ViewGroup. Example:

    yourViewGroup.forEach{ childView -> // do something with this childView }

    2 - Return a list of childViews using .children.toList in a ViewGroup

    To return a list of Views, you can use function children to return a Sequence and then use toList() to transform it to a List. Example:

    val yourChildViewsList: List = yourViewGroup.children.toList()

提交回复
热议问题