如何移除Jetpack Compose中OutlinedTextField聚焦及输入状态下的下划线且不改变其颜色
移除OutlinedTextField聚焦状态下的下划线(不改动原有颜色)
嘿,我完全get到你的需求了——要去掉OutlinedTextField聚焦时的下划线,还不能碰它原本的任何颜色对吧?这就给你搞定!
解决方案思路
在Jetpack Compose里,OutlinedTextField的下划线(包括未聚焦时的底部线和聚焦时的外框底部部分)是由indicator和border共同控制的。我们可以通过自定义文本字段的颜色配置,把下划线对应的颜色设为透明,同时保留所有其他原有颜色(比如边框、标签、图标、占位符的颜色)。
修改后的完整代码
直接把下面的代码替换你原来的OutlinedTextField即可:
OutlinedTextField( modifier = Modifier .fillMaxWidth() .padding(16.dp), value = password, onValueChange = { password = it }, leadingIcon = { Icon( painter = painterResource(id = R.drawable.ic_baseline_vpn_key_24), contentDescription = "icon-content" ) }, trailingIcon = { IconButton(onClick = { passwordVisibility = !passwordVisibility }) { Icon(painter = icon, contentDescription = "show-password") } }, placeholder = { Text(text = "Password", color = Color.LightGray) }, label = { BasicText(text = "Password") }, visualTransformation = if (passwordVisibility) VisualTransformation.None else PasswordVisualTransformation(), // 核心配置:移除下划线,保留原有颜色 colors = TextFieldDefaults.outlinedTextFieldColors( // 把聚焦和非聚焦状态的下划线设为透明 focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, // 显式指定边框颜色为主题默认值,确保不改动原有样式 focusedBorderColor = MaterialTheme.colors.outline, unfocusedBorderColor = MaterialTheme.colors.outline.copy(alpha = 0.6f) ) )
为什么这么做?
focusedIndicatorColor和unfocusedIndicatorColor控制的就是文本字段的下划线颜色,设为透明后就看不到下划线了。- 我们显式指定了
focusedBorderColor和unfocusedBorderColor为主题默认的轮廓色,这样就不会影响你原来设置的其他颜色(比如占位符的浅灰色、标签文本颜色等)。 - 所有你原来配置的属性(比如图标、占位符、密码可见性切换)都完全保留,只是去掉了讨厌的下划线。
内容的提问来源于stack exchange,提问作者EKREM YİĞİT
相关产品推荐
相关产品推荐

