Jetpack Compose:如何判断Text组件内容是否超过9行并控制按钮显示
I totally get what you're trying to pull off here—having a button pop up only when your Text component wraps beyond 9 lines. The trick here is using Compose's TextLayoutResult to dynamically detect how many lines the text is actually using, then toggle the button's visibility based on that count.
Here's a complete, working example tailored to your code:
@Composable fun ExpandableTextWithToggleButton() { val sampleText = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. " + "Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, " + "when an unknown printer took a galley of type and scrambled it to make a type specimen book. " + "It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software " + "like Aldus PageMaker including versions of Lorem Ipsum." // Track whether we need to show the button var showButton by remember { mutableStateOf(false) } Column( modifier = Modifier.padding(16.dp) ) { Text( text = sampleText, modifier = Modifier.padding(bottom = 4.dp), fontSize = 16.sp, textAlign = TextAlign.Start, style = MaterialTheme.typography.body1, // This callback runs after the text is laid out on screen onTextLayout = { layoutResult -> // Update our state if the line count crosses the 9-line threshold showButton = layoutResult.lineCount > 9 } ) // Only render the button if our state says it should be visible if (showButton) { Button( onClick = { /* Add your button action here (e.g., expand text) */ }, modifier = Modifier.padding(top = 8.dp) ) { Text("Read More") } } } }
A quick breakdown of how this works:
- We use
rememberto hold theshowButtonstate—this keeps the value intact across recompositions so it doesn't reset every time the UI updates. - The
onTextLayoutcallback in theTextcomponent fires after the text is fully rendered. TheTextLayoutResultit provides gives us the actual number of lines the text is using (not just the content length). - We check if the line count is greater than 9, then update our state to toggle the button.
- Finally, we conditionally render the Button based on that state.
Key things to keep in mind:
- Don't set
maxLineson the Text component if you want an accurate line count—setting it would truncate the text, making the line count lower than the full content's actual line count. - If your text content changes dynamically (e.g., loading from an API), this setup will automatically re-calculate the line count and update the button visibility, since
onTextLayoutre-runs whenever the text or layout changes.
内容的提问来源于stack exchange,提问作者prat
相关产品推荐
相关产品推荐

