前言

自从去年参加 Android 官方发起了 Jetpack Compose 的推广活动:Jetpack Compose 开发者挑战赛以后,再未系统的学习过 Jetpack Compose 的内容,一晃一年就过去了,官方版本已经更新至稳定版 本1.1.1,Alpha 版本 1.2.0-alpha04

从今天开始,继续自学 Jetpack Compose,就从文本 Text 开始吧,用不用得上再说。

Text

属性

@Composable
fun Text(text: String,modifier: Modifier = Modifier,color: Color = Color.Unspecified,fontSize: TextUnit = TextUnit.Unspecified,fontStyle: FontStyle? = null,fontWeight: FontWeight? = null,fontFamily: FontFamily? = null,letterSpacing: TextUnit = TextUnit.Unspecified,textDecoration: TextDecoration? = null,textAlign: TextAlign? = null,lineHeight: TextUnit = TextUnit.Unspecified,overflow: TextOverflow = TextOverflow.Clip,softWrap: Boolean = true,maxLines: Int = Int.MAX_VALUE,onTextLayout: (TextLayoutResult) -> Unit = {},style: TextStyle = LocalTextStyle.current
)
属性 含义
text 文本内容
modifer 修饰器
color 文本颜色
fontSize 文本大小
fontStyle 字体样式
fontWeight 文本粗细
fontFamily 文本字体
letterSpacing 文字间隔
textDecoration 文本装饰
textAlign 文本对齐方式
lineHeight 行高
overflow 文本溢出处理方式
softWrap 自动换行
maxLines 最大显示行数
onTextLayout 计算布局回调函数
style 文本样式

另外还有一个 Text 函数,大同小异,多出两个属性。

@Composable
fun Text(text: AnnotatedString,modifier: Modifier = Modifier,color: Color = Color.Unspecified,fontSize: TextUnit = TextUnit.Unspecified,fontStyle: FontStyle? = null,fontWeight: FontWeight? = null,fontFamily: FontFamily? = null,letterSpacing: TextUnit = TextUnit.Unspecified,textDecoration: TextDecoration? = null,textAlign: TextAlign? = null,lineHeight: TextUnit = TextUnit.Unspecified,overflow: TextOverflow = TextOverflow.Clip,softWrap: Boolean = true,maxLines: Int = Int.MAX_VALUE,inlineContent: Map<String, InlineTextContent> = mapOf(),onTextLayout: (TextLayoutResult) -> Unit = {},style: TextStyle = LocalTextStyle.current
)
属性 含义
text AnnotatedString 类型,可显示内容更加丰富
inlineContent 内联内容

属性示例

color

val colors = listOf(Purple200, Purple500, Purple700)
items(3) {Text(text = "假如我是一只鸟,", color = colors[it])
}

fontSize

items(3) {Text(text = "我也应该用嘶哑的喉咙歌唱,", fontSize = (12 * (it + 1)).sp)
}

fontStyle

items(2) {Text(text = "这被暴风雨所打击着的土地,", fontStyle = FontStyle.values()[it])
}

fontWeight

items(9) {Text(text = "这永远汹涌着我们的悲愤的河流,", fontWeight = FontWeight(100 * (it + 1)))
}

fontFamily

@Composable
fun FontFamilySansSerifSample() {Text(text = "Demo Text sans-serif",fontFamily = FontFamily.SansSerif)
}@Composable
fun FontFamilySerifSample() {Text(text = "Demo Text serif",fontFamily = FontFamily.Serif)
}@Composable
fun FontFamilyMonospaceSample() {Text(text = "Demo Text monospace",fontFamily = FontFamily.Monospace)
}@Composable
fun FontFamilyCursiveSample() {Text(text = "Demo Text cursive",fontFamily = FontFamily.Cursive)
}@Composable
fun CustomFontFamilySample() {val fontFamily = FontFamily(Font(resId = R.font.myfont_regular,weight = FontWeight.W400,style = FontStyle.Normal),Font(resId = R.font.myfont_italic,weight = FontWeight.W400,style = FontStyle.Italic))Text(text = "Demo Text", fontFamily = fontFamily)
}@Composable
fun FontFamilySynthesisSample() {// The font family contains a single font, with normal weightval fontFamily = FontFamily(Font(resId = R.font.myfont_regular, weight = FontWeight.Normal))// Configuring the Text composable to be bold// Using FontSynthesis.Weight to have the system render the font bold my making the glyphs// thickerText(text = "Demo Text",style = TextStyle(fontFamily = fontFamily,fontWeight = FontWeight.Bold,fontSynthesis = FontSynthesis.Weight))
}

letterSpacing

items(5) {Text(text = "和那来自林间的无比温柔的黎明,", letterSpacing = (it * 5).sp)
}

textDecoration

@Composable
fun TextDecorationLineThroughSample() {Text(text = "Demo Text",textDecoration = TextDecoration.LineThrough)
}@Composable
fun TextDecorationUnderlineSample() {Text(text = "Demo Text",textDecoration = TextDecoration.Underline)
}@Composable
fun TextDecorationCombinedSample() {Text(text = "Demo Text",textDecoration = TextDecoration.Underline + TextDecoration.LineThrough)
}

textAlign

val textAligns = listOf(TextAlign.Left,TextAlign.Right,TextAlign.Center,TextAlign.Justify,TextAlign.Start,TextAlign.End
)
items(6) {Text(modifier = Modifier.fillMaxWidth(),text = "——连羽毛也腐烂在土地里面,",textAlign = textAligns[it])
}

lineHeight

items(4) {Text(modifier = Modifier.fillMaxWidth(),text = "上帝, 请赐予我平静, 去接受我无法改变的. 给予我勇气, 去改变我能改变的, 赐我智慧, 分辨这两者的区别.",lineHeight = (20 * (it + 1)).sp)
}

overflow

@Composable
fun TextOverflowClipSample() {Text(text = "Hello ".repeat(2),modifier = Modifier.size(100.dp, 70.dp).background(Color.Cyan),fontSize = 35.sp,overflow = TextOverflow.Clip)
}@Composable
fun TextOverflowEllipsisSample() {Text(text = "Hello ".repeat(2),modifier = Modifier.width(100.dp).background(Color.Cyan),fontSize = 35.sp,overflow = TextOverflow.Ellipsis,maxLines = 1)
}@Composable
fun TextOverflowVisibleFixedSizeSample() {val background = remember { mutableStateOf(Color.Cyan) }Box(modifier = Modifier.size(100.dp, 100.dp)) {Text(text = "Hello ".repeat(2),modifier = Modifier.size(100.dp, 70.dp).background(background.value).clickable {background.value = if (background.value == Color.Cyan) {Color.Gray} else {Color.Cyan}},fontSize = 35.sp,overflow = TextOverflow.Visible)}
}@Composable
fun TextOverflowVisibleMinHeightSample() {val background = remember { mutableStateOf(Color.Cyan) }val count = remember { mutableStateOf(1) }Box(modifier = Modifier.size(100.dp, 100.dp)) {Text(text = "Hello".repeat(count.value),modifier = Modifier.width(100.dp).heightIn(min = 70.dp).background(background.value).clickable {background.value =if (background.value == Color.Cyan) Color.Gray else Color.Cyancount.value = if (count.value == 1) 2 else 1},fontSize = 35.sp,overflow = TextOverflow.Visible)}
}

softWrap

items(2) {Text(modifier = Modifier.fillMaxWidth(),text = "上帝, 请赐予我平静, 去接受我无法改变的. 给予我勇气, 去改变我能改变的, 赐我智慧, 分辨这两者的区别.",softWrap = it == 1)
}

maxLines

item {Text(text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " +"incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis " +"nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",maxLines = 2)
}

onTextLayout

item {Text(modifier = Modifier.fillMaxWidth(),text = "上帝, 请赐予我平静, 去接受我无法改变的. 给予我勇气, 去改变我能改变的, 赐我智慧, 分辨这两者的区别.",onTextLayout = {appLog("onTextLayout => size: ${it.size}")})
}

textStyle

@Composable
fun TextStyleSample() {Text(text = "Demo Text",style = TextStyle(color = Color.Red,fontSize = 16.sp,fontFamily = FontFamily.Monospace,fontWeight = FontWeight.W800,fontStyle = FontStyle.Italic,letterSpacing = 0.5.em,background = Color.LightGray,textDecoration = TextDecoration.Underline))
}

annotatedString

Text(text = with(AnnotatedString.Builder("Hello")) {// push green text style so that any appended text will be greenpushStyle(SpanStyle(color = Color.Green))// append new text, this text will be rendered as greenappend(" World")// pop the green stylepop()// append a string without styleappend("!")// then style the last added word as red, exclamation mark will be redaddStyle(SpanStyle(color = Color.Red), "Hello World".length, this.length)toAnnotatedString()
})

inlineTextContent

@Composable
fun InlineTextContentSample() {val myId = "inlineContent"val text = buildAnnotatedString {append("Hello")// Append a placeholder string "[myBox]" and attach an annotation "inlineContent" on it.appendInlineContent(myId, "[myBox]")}val inlineContent = mapOf(Pair(// This tells the [BasicText] to replace the placeholder string "[myBox]" by// the composable given in the [InlineTextContent] object.myId,InlineTextContent(// Placeholder tells text layout the expected size and vertical alignment of// children composable.Placeholder(width = 0.5.em,height = 0.5.em,placeholderVerticalAlign = PlaceholderVerticalAlign.AboveBaseline)) {// This [Box] will fill maximum size, which is specified by the [Placeholder]// above. Notice the width and height in [Placeholder] are specified in TextUnit,// and are converted into pixel by text layout.Box(modifier = Modifier.fillMaxSize().background(color = Color.Red))}))Text(text = text, inlineContent = inlineContent)
}

onTextLayout

Text(modifier = Modifier.fillMaxWidth(),text = "上帝, 请赐予我平静, 去接受我无法改变的. 给予我勇气, 去改变我能改变的, 赐我智慧, 分辨这两者的区别.",onTextLayout = {appLog("onTextLayout => size: ${it.size}")}
)

可选择文本

SelectionContainer(modifier = Modifier.fillMaxWidth()) {Text(text = "You can select me, baby")
}

可点击文本

方式一:Modifier.clickable

Text(text = "使用 clickable 实现点击",modifier = Modifier.clickable {appLog("使用 Text clickable 属性完成点击")})

方式二:ClickableText

ClickableText(text = AnnotatedString(text = "Hello World",// make "Hello" italic.spanStyles = listOf(AnnotatedString.Range(SpanStyle(fontStyle = FontStyle.Italic), 0, 5)),// create two paragraphs with different alignment and indent settings.paragraphStyles = listOf(AnnotatedString.Range(ParagraphStyle(textAlign = TextAlign.Center), 0, 6),AnnotatedString.Range(ParagraphStyle(textIndent = TextIndent(5.sp)), 6, 11))), onClick = {appLog("ClickableText 完成点击, 位置 $it")}
)

源码

https://github.com/onlyloveyd/LearningCompose

Jetpack Compose(一):Text相关推荐

  1. Android: Jetpack Compose如何禁用涟漪(水波纹)效果

    系列文章目录 Android: Jetpack Compose如何禁用涟漪(水波纹)效果 Android:使用Jetpack Compose 实现Text控件跑马灯效果 Android:使用Jetpa ...

  2. 随输入动态改变ui_深入详解 Jetpack Compose | 优化 UI 构建

    人们对于 UI 开发的预期已经不同往昔.现如今,为了满足用户的需求,我们构建的应用必须包含完善的用户界面,其中必然包括动画 (animation) 和动效 (motion),这些诉求在 UI 工具包创 ...

  3. Jetpack Compose Animations 超简单教程

    Node:本文基于Jetpack Compose 1.0.0-beta01 Animation是由state驱动的 Compose的核心思想状态驱动UI刷新,这一思想同样体现在动画上. Compose ...

  4. Jetpack Compose入门详解(实时更新)

    Jetpack Compose入门详解 前排提醒 前言(Compose是什么) 1.实战准备 一.优势与缺点 二.前四课 三.标准布局组件 1.Column 2.Row 3.Box 四.xml和com ...

  5. Jetpack Compose中的Modifier

    Modifier的基本使用 Modifier修饰符是Jetpack Compose中用来修饰组件的,提供常用的属性,写布局时几乎所有Composable组件的大部分属性都可以用Modifier 来修饰 ...

  6. 安卓开发: Jetpack compose + kotlin 实现 俄罗斯方块游戏

    文章目录 前言 俄罗斯方块开发文档 1.摘要 2.开发工具选取 2.1.Compose 的自身优点 2.2.数据驱动界面 3.设计需求 3.1.功能需求 3.1.1.基本游戏功能 3.1.2.拓展功能 ...

  7. Jetpack Compose for Desktop: 里程碑1发布

    在深入详解 Jetpack Compose | 优化 UI 构建 中谷歌介绍了为什么要设计 Jetpack Compose 来完成原生 Android 的开发,如今 Jetpack Compose f ...

  8. Jetpack Compose中的手势操作

    点击事件 监听点击事件非常简单,使用 clickable 和 combinedClickable 修饰符即可满足需求: @OptIn(ExperimentalFoundationApi::class) ...

  9. 详解Jetpack Compose中的Modifier修饰符

    前言 本文将会介绍Jetpack Compose中的Modifier.在谷歌官方文档中它的描述是这么一句话:Modifier元素是一个有序.不可变的集合,它可以往Jetpack Compose UI元 ...

最新文章

  1. python爬虫框架排行榜-哪种Python框架适合你?简单介绍几种主流Python框架
  2. java用毫秒数做日期计算的一个踩坑记录
  3. IDE / Qt / 浅谈 qmake 之 pro、pri、prf、prl文件
  4. 【论文笔记】HyperFace: ADeep Multi-task Learning Framework for Face Detection
  5. python 公众号文章发布_Python获取公众号文章
  6. 计算机综合布线课程,综合布线工程课程教与学(教学大纲)
  7. 数据分析 超市条码_条码的应用
  8. 苹果商店上架流程_苹果app上架流程
  9. 谷歌 Jason Wei | AI 研究的 4 项基本技能
  10. 【JavaWeb】JQuery实现广告显示和隐藏动画效果
  11. 数值计算之 拟合法,线性拟合,多项式拟合
  12. 微信小程序 post请求发送x-www-form-urlencoded类型数据
  13. BN/Batch Norm中的滑动平均/移动平均/Moving Average
  14. TiDB数据库schema设计之表结构设计
  15. “AI+教育”想做好有多难?网易有道CEO、学霸君CEO等4位大佬“掏心窝”...
  16. Bigtable学习翻译
  17. she was A Phantom Of Delight
  18. VC删除注册表键值项
  19. 平台 恒鑫 机器人_压铸取放件机器人系统-恒鑫智能
  20. 基于layui实现的日历记事本

热门文章

  1. 试用期、加班时间、加班补偿——职场常见知识《劳动法》
  2. BPSK信号产生(二)--载波调制
  3. acwing基础课——Dijkstra
  4. 即有集团:品牌化运作成为集团发展“新基因”
  5. 使用MyQR制作二维码
  6. mac word打印一张红色(带颜色)的A4纸
  7. android 代码等待一秒,【报Bug】安卓微信旧版本7.0.2 ,支付完成,等待几秒后,再点击完成 回到小程序,跳转不了页面。...
  8. windows下使用命令行运行PHP
  9. 华硕z97不识别m2固态_华硕主板Z97-A无法识别intel M.2 NVME固态硬盘的解决方法
  10. vue3出现此警告信息:[Vue warn]: Failed to resolve component: dpan