Search code examples
androidandroid-jetpack-composelazycolumnandroid-jetpack-compose-lazy-column

How to get firstvisibleItemIndex in detectTapGestures


I have a lazycolumn and use detectTapGestures to get the onclick event

I would like to get the current firstvisibleItemIndex of the lazycolumn when I click on a Lazycolumn item

Tried different solutions with state.firstVisibleItemIndex but none is working - how can I start?

Card(colors = CardDefaults.cardColors(
        containerColor = Color(0xFF7DCEA0), Color.Black
    ),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        modifier = Modifier
            .padding(horizontal = 6.dp, vertical = 6.dp)
            .offset { IntOffset(swipeableState.offset.value.roundToInt(), 0) }
            .pointerInput(Unit) {

                detectTapGestures(

                    onLongPress = {
                     //   val firstVisibleItemIndex = state.firstVisibleItemIndex

                      
                        mContext.startActivity(Intent(mContext, LKList::class.java))
                    },

                    onTap = {
                        Log.e(
                            "TestX",
                            ">>>>>> DCMainItem : On Tap"
                        )
                      
                        mContext.startActivity(Intent(mContext, DCInfo::class.java))
                    }
                )

Solution

  • You can use something like:

        val listState = rememberLazyListState()
    
        LazyColumn(state = listState) {
    
            items(itemsList) {
                Text("Item is $it",
                    modifier = Modifier
                        .pointerInput(Unit) {
                            detectTapGestures(
                                onLongPress = {
                                    val firstVisibleItemIndex = listState.firstVisibleItemIndex
                                    //....
                                },
                            )
                        }
                )
            }
        }