1、Text的简单用法
package com.example.mycompose.ui.theme.components
import androidx.compose.runtime.Composable
import androidx.compose.material.Text
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.sp
import com.example.mycompose.R
@Composable
fun TextSample() {
//直接设置字体
//Text(text = "我终于学会Jetpack Compose 了!")
Text(
text = stringResource(id = R.string.text),//从xml中读取字体内容
color = Color(255, 255, 255),//设置字体颜色
fontSize = 16.sp,//设置字体大小
letterSpacing = 18.sp,//设置字体间距
textDecoration = TextDecoration.combine(//设置字体的下划线
listOf(
TextDecoration.LineThrough,
TextDecoration.Underline
)
),
textAlign = TextAlign.Center,//文字居中显示
maxLines = 2, //显示的行数
overflow = TextOverflow.Ellipsis //文本显示不全显示...
)
}
@Preview
@Composable
fun TextSamplePreview() {
TextSample()
}
2、Text的高级用法
①长按出现copy复制选项
SelectionContainer() {
Text(
text = "我终于学会Jetpack Compose 了!",//从xml中读取字体内容
fontSize = 16.sp,//设置字体大小
overflow = TextOverflow.Ellipsis, //文本显示不全显示...
)
}
②获取点击的文字位置
ClickableText(text = buildAnnotatedString {
append("我终于学会Jetpack Compose 了!")
}, onClick = {
Log.d("TextSample","你点击到我了: $it")
})
③点击特定区域时触发点击回调
val annotationString = buildAnnotatedString {
append("点击登陆那代表您已知悉和同意")
//往字符串中添加注解,tag为标识,直到遇到pop()
pushStringAnnotation("protocol","https://docs.bughub.icu/compose")
withStyle(style = SpanStyle(Color.Blue, textDecoration = TextDecoration.Underline)){
append("用户协议")
}
pop()
append("和")
//往字符串中添加注解,tag为标识,直到遇到pop()
pushStringAnnotation("privacy","https://github.com/RandyWei")
withStyle(style = SpanStyle(Color.Blue, textDecoration = TextDecoration.Underline)){
append("隐私政策")
}
pop()
}
ClickableText(text = annotationString, onClick = { offset ->
//从字符串中根据tag查找注释
annotationString.getStringAnnotations("protocol",start = offset,end = offset).firstOrNull()
?.let { annotation ->
Log.d("TextSample","你点击到我了: ${annotation.item}")
}
annotationString.getStringAnnotations("privacy",start = offset,end = offset).firstOrNull()
?.let { annotation ->
Log.d("TextSample","你点击到我了: ${annotation.item}")
}
})
只有点击了带有下划线的蓝色区域时才会打印,点击其它部分没反应
注:
1、参考资料:
2、Android View和Compose相应view对照表