Jetpack Compose中OutlinedButton文本左对齐失效如何解决
问题核心在于OutlinedButton默认的内容布局是居中对齐,哪怕你给Text设置了textAlign = TextAlign.Left,也只是让Text在自身的小范围内左对齐,整体仍被Button的居中布局限制在中间位置。
下面提供两种直接有效的解决方式:
方式一:让Text填充Button全部宽度
给Text的Modifier添加fillMaxWidth(),让Text占满Button的整个宽度,此时textAlign.Left就能生效,文本会靠左显示:
OutlinedButton( colors = ButtonDefaults.outlinedButtonColors(Color.Transparent), border = BorderStroke(0.dp, Color.Transparent), modifier = Modifier.fillMaxWidth() .background( color = Color.Transparent, shape = RectangleShape ), onClick = {} ) { Text( modifier = Modifier.fillMaxWidth() // 添加该行 .padding(horizontal = 0.dp, vertical = 0.dp), color = Color.Black, text = text, textAlign = TextAlign.Left, fontSize = 15.sp, ) }
方式二:修改Button的内容对齐规则
直接在OutlinedButton的参数里设置contentAlignment = Alignment.CenterStart,把Button内部内容的默认居中对齐改成左对齐,这种方式无需修改Text的Modifier:
OutlinedButton( colors = ButtonDefaults.outlinedButtonColors(Color.Transparent), border = BorderStroke(0.dp, Color.Transparent), modifier = Modifier.fillMaxWidth() .background( color = Color.Transparent, shape = RectangleShape ), onClick = {}, contentAlignment = Alignment.CenterStart // 添加该行 ) { Text( modifier = Modifier.padding(horizontal = 0.dp, vertical = 0.dp), color = Color.Black, text = text, fontSize = 15.sp, ) }
两种方法都能解决文本居中的问题,你可以根据需求选择:需要Text占满Button宽度就用第一种,否则第二种更简洁。
内容的提问来源于stack exchange,提问作者nikhilbalwani
相关产品推荐
相关产品推荐

