Enabling Text Selection in Compose LazyColumn by selection container

422 views Asked by At

I previously used a WebView to display a long text and style each word based on some business logic. However, I recently transformed this HTML content into a list of sentences and utilized a LazyColumn to present it in my Compose application.

One of the features I cherished in my previous implementation was the ability to select text and utilize the pop-up options for actions like copying or sharing.

I've attempted to wrap my LazyColumn in a SelectionContainer within Jetpack Compose, but it's currently preventing me from selecting text across different items in the list.

I'm curious if there is a way to retain the same text selection behavior in my new Compose structure. Any suggestions or insights would be greatly appreciated.

I have tried these ones so far:

  LazyColumn(
    modifier = Modifier.fillMaxSize(),
    content = {
        items(sentenceList) { index ->
            SelectionContainer {
                Text(
                    text = sentenceList[index]
                )
            }
        }
    }
)

and this:

SelectionContainer {
  LazyColumn(
        modifier = Modifier.fillMaxSize(),
        content = {
            items(sentenceList) { index ->
                    Text(
                        text = sentenceList[index]
                    )
                }
            }
    )
 }

update1:

I should mention that the second option does work, but there's an issue that arises when you try to scroll up and down and then attempt to long-press for text selection again; strangely, it stops working.

1

There are 1 answers

3
Chirag Thummar On

I think you may be missing State of LazyColumn. I have tried below code and it works for me.

Try This

@Preview(showBackground = true)
@Composable
 fun TestPreview() {
    LazyColumn(
        state = rememberLazyListState(),
        modifier = Modifier.fillMaxSize(),
        content = {
            items(65) { index ->
                SelectionContainer {
                    Text(
                        text = "I have pasted long text for text selection demo."
                    )
                }
            }
        }
    )

}