You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 02:37:39