Hi everyone, just wanted to ask if i have one Lazy...
# compose
s
Hi everyone, just wanted to ask if i have one LazyColumn, and data list is dynamic, and for each item i need its global offset position. So im using remebered state variable for that and updating that using onGloballyPositioned modifier for each item. Is it fine to do that for each item inside items, or it can be bad practice and there can be a better alternative for this? Actually i need that global offset position during onLongPress on item. I know onLongPress also provides offset but that is relative to item composable but i need global position of each item while longPressing it.
n
In Jetpack Compose, using
onGloballyPositioned
to get the global position of each item inside a
LazyColumn
is technically feasible, but it can lead to performance issues, especially with a dynamic and potentially large list. Each recomposition of an item in the list will trigger the
onGloballyPositioned
callback, which can be inefficient if the list updates frequently or contains many items.
s
Yeah exactly, performance is my main concern. Thats why i asked this question. So then is there any other way out for getting that done?
n
Instead of calculating the global position of each item upfront and storing it, consider capturing the global position when the long press event occurs. I think you can do this by using the
Modifier.pointerInput
in combination with
detectTapGestures
for handling long presses directly.
Try something like this: @Composable fun MyList(items: List<String>) { LazyColumn { items(items) { item -> ListItem(item = item, onLongPress = { globalOffset -> println(“Global position: $globalOffset”) }) } } } @Composable fun ListItem(item: String, onLongPress: (Offset) -> Unit) { val view = LocalView.current val density = LocalDensity.current Box( modifier = Modifier .pointerInput(Unit) { detectTapGestures( onLongPress = { offset -> val locationOnScreen = IntArray(2) view.getLocationOnScreen(locationOnScreen) val globalX = locationOnScreen[0] + with(density) { offset.x.toPx() } val globalY = locationOnScreen[1] + with(density) { offset.y.toPx() } onLongPress(Offset(globalX, globalY)) } ) } ) { // Your item’s UI goes here } }
s
Wow, thats great. I was not even aware about this getLocationOnScreen method until now. Yes now it should work. Thanku so much. I will check it and update you. 🙏
👍 1
Hi @Natasha Jordanovska it not working. i guess getLocationOnScreen is returning the value almost similar to offset provided by onLongPress (tap position relative to current item composable) but not relative to device screen
n
Try to capture the
LocalView.current
in the parent composable that contains your list and pass it to Each Child (ListItem)
s
Still same location,I tried passing it from parent of list.
133 Views