Compose BasicTextField拖拽光标时文本不滚动问题求助
解决Jetpack Compose BasicTextField拖拽光标文本不滚动问题
问题原因
当BasicTextField设置singleLine = true且textAlign = TextAlign.Center时,文本超出容器宽度后,拖拽光标不会触发文本滚动——居中对齐逻辑会让文本始终保持在可视区域中间,无法跟随光标位置滚动。
解决方案
方案1:移除文本居中对齐(简单直接)
去掉textAlign = TextAlign.Center,让文本默认左对齐,拖拽光标时文本会自动滚动:
var text by remember { mutableStateOf("123456789123456") } Box(contentAlignment = Alignment.Center) { BasicTextField( modifier = Modifier .width(100.dp) .height(40.dp) .background(color = Color.LightGray) .wrapContentHeight(align = Alignment.CenterVertically), textStyle = TextStyle.Default.copy( fontSize = 14.sp, fontWeight = FontWeight.Bold ), value = text, singleLine = true, onValueChange = { text = it }, ) }
方案2:保留视觉居中并实现滚动(复杂场景)
如果需要保持文本居中的视觉效果,可通过添加水平滚动状态、监听光标位置手动控制滚动:
var text by remember { mutableStateOf("123456789123456") } val scrollState = rememberScrollState() val coroutineScope = rememberCoroutineScope() val containerWidth = 100.dp Box(contentAlignment = Alignment.Center) { BasicTextField( modifier = Modifier .width(containerWidth) .height(40.dp) .background(color = Color.LightGray) .wrapContentHeight(align = Alignment.CenterVertically) .horizontalScroll(scrollState), textStyle = TextStyle.Default.copy( fontSize = 14.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center ), value = text, singleLine = true, onValueChange = { text = it }, onTextLayout = { layoutResult -> val cursorX = layoutResult.getCursorRect(text.length).centerX() val containerPx = containerWidth.toPx() // 计算滚动偏移,确保光标始终在可视区域内 val targetOffset = (cursorX - containerPx / 2).toInt() coroutineScope.launch { scrollState.animateScrollTo(targetOffset) } } ) }
内容的提问来源于stack exchange,提问作者seven years
相关产品推荐
相关产品推荐

