Jetpack Compose固定高度滚动Box中TextStyle(下划线/删除线)异常求助
解决Jetpack Compose中固定高度滚动容器下文本装饰失效问题
当给Box同时设置固定高度和verticalScroll修饰符后,文本的下划线、删除线等装饰失效,这是因为verticalScroll直接作用在Box上时,会改变容器内部的布局测量逻辑,导致Text无法正确计算文本装饰的绘制区域。
解决方案
把滚动修饰符从Box移到内部的Column容器上,让Box负责固定高度,内部Column处理滚动,这样既能保留固定高度和滚动效果,又能让文本装饰正常工作。
修改后的代码
@Composable fun TextDecorationExample() { var isUnderlined by remember { mutableStateOf(false) } var isStrikethrough by remember { mutableStateOf(false) } var isBold by remember { mutableStateOf(false) } var isItalic by remember { mutableStateOf(false) } val scrollState = rememberScrollState() Column(modifier = Modifier .fillMaxSize() .padding(16.dp) ) { Box( modifier = Modifier .fillMaxWidth() .height(200.dp) // 保留固定高度 .border(2.dp, Color.White) .padding(10.dp) ) { // 用Column包裹Text,并给Column加verticalScroll Column(modifier = Modifier.verticalScroll(scrollState)) { Text( text = "Hello, Jetpack Compose! " + "This is a long text to demonstrate vertical scrolling. " + "You can apply various text styles like underline, strikethrough, bold, and italic.", color = Color.White, style = TextStyle( fontSize = 24.sp, textDecoration = when { isUnderlined && isStrikethrough -> TextDecoration.Underline + TextDecoration.LineThrough isUnderlined -> TextDecoration.Underline isStrikethrough -> TextDecoration.LineThrough else -> null }, fontWeight = if (isBold) FontWeight.Bold else FontWeight.Normal, fontStyle = if (isItalic) FontStyle.Italic else FontStyle.Normal ), modifier = Modifier.padding(bottom = 16.dp) ) } } // 按钮部分保持不变 Button(onClick = { isUnderlined = !isUnderlined }, colors = ButtonDefaults.buttonColors( contentColor = if (isUnderlined) Color.Black else Color.White, containerColor = if (isUnderlined) Color.Green else Color.Gray ), modifier = Modifier.padding(top = 8.dp)) { Text(text = "Underline") } Button(onClick = { isStrikethrough = !isStrikethrough }, colors = ButtonDefaults.buttonColors( contentColor = if (isStrikethrough) Color.Black else Color.White, containerColor = if (isStrikethrough) Color.Green else Color.Gray ), modifier = Modifier.padding(top = 8.dp)) { Text(text = "Strikethrough") } Button(onClick = { isBold = !isBold }, colors = ButtonDefaults.buttonColors( contentColor = if (isBold) Color.Black else Color.White, containerColor = if (isBold) Color.Green else Color.Gray ), modifier = Modifier.padding(top = 8.dp)) { Text(text = "Bold") } Button(onClick = { isItalic = !isItalic }, colors = ButtonDefaults.buttonColors( contentColor = if (isItalic) Color.Black else Color.White, containerColor = if (isItalic) Color.Green else Color.Gray ), modifier = Modifier.padding(top = 8.dp) ) { Text(text = "Italic") } } }
原理说明
Box是单一子元素容器,直接给它加verticalScroll会让内部Text的布局被强制适配滚动容器的约束,导致文本装饰的绘制逻辑异常。换成Column包裹Text并承担滚动功能后,Column能正确处理文本的布局测量,让Text的下划线、删除线等装饰正常渲染,同时Box的固定高度依然能限制滚动区域的显示大小,完美满足需求。
内容的提问来源于stack exchange,提问作者J K
相关产品推荐
相关产品推荐

