Jetpack Compose 中如何自定义 ClickableText 的字体与颜色样式
你可以通过ClickableText的style参数传入自定义TextStyle实现字体、颜色的自定义配置,具体实现如下:
基础自定义样式
ClickableText( text = AnnotatedString(stringResource(R.string.forgot_password)), // 新增style参数配置文本样式 style = TextStyle( color = Color(0xFF1677ff), // 替换为你需要的颜色值 fontSize = 14.sp, fontFamily = FontFamily.SansSerif, // 可替换为系统内置字体或自定义字体 fontWeight = FontWeight.Normal ), onClick = { offset -> Log.d("ClickableText", "$offset -th character is clicked.") } )
自定义本地字体配置
如果需要使用项目导入的自定义字体,先将字体文件放入res/font/目录下,再按以下方式加载使用:
// 加载自定义字体 val customFontFamily = FontFamily( Font(R.font.your_custom_font_name, FontWeight.Normal) ) // 替换到TextStyle中即可 ClickableText( text = AnnotatedString(stringResource(R.string.forgot_password)), style = TextStyle( color = Color(0xFF1677ff), fontFamily = customFontFamily ), onClick = { offset -> Log.d("ClickableText", "$offset -th character is clicked.") } )
可选:状态联动样式(如按压变色)
如果需要实现点击按下时的样式变化,可以配合interactionSource监听交互状态动态修改样式:
val interactionSource = remember { MutableInteractionSource() } val isPressed by interactionSource.collectIsPressedAsState() // 按压时切换为灰色,正常状态为蓝色 val textColor = if (isPressed) Color.Gray else Color(0xFF1677ff) ClickableText( text = AnnotatedString(stringResource(R.string.forgot_password)), style = TextStyle( color = textColor, fontSize = 14.sp ), interactionSource = interactionSource, onClick = { offset -> Log.d("ClickableText", "$offset -th character is clicked.") } )
内容的提问来源于stack exchange,提问作者Seb
相关产品推荐
相关产品推荐

