Jetpack Compose 入门教程之Text

news2024/9/22 8:33:50

这个文本显示组件应该是我们最常用的组件,下面会非常细

归纳

实例


下面一一演示这些属性与控制逻辑

文本的展示


Text组件 所有构造方法都是text:String,要想用string.xml里面的字符串资源 得使用

stringResource方法,其相似方法如下

/*
 * Copyright 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package androidx.compose.ui.res

import androidx.annotation.ArrayRes
import androidx.annotation.PluralsRes
import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable

/**
 * Load a string resource.
 *
 * @param id the resource identifier
 * @return the string data associated with the resource
 */
@Composable
@ReadOnlyComposable
fun stringResource(@StringRes id: Int): String {
    val resources = resources()
    return resources.getString(id)
}

/**
 * Load a string resource with formatting.
 *
 * @param id the resource identifier
 * @param formatArgs the format arguments
 * @return the string data associated with the resource
 */
@Composable
@ReadOnlyComposable
fun stringResource(@StringRes id: Int, vararg formatArgs: Any): String {
    val resources = resources()
    return resources.getString(id, *formatArgs)
}

/**
 * Load a string resource.
 *
 * @param id the resource identifier
 * @return the string data associated with the resource
 */
@Composable
@ReadOnlyComposable
fun stringArrayResource(@ArrayRes id: Int): Array<String> {
    val resources = resources()
    return resources.getStringArray(id)
}

/**
 * Load a plurals resource.
 *
 * @param id the resource identifier
 * @param count the count
 * @return the pluralized string data associated with the resource
 */
@Composable
@ReadOnlyComposable
fun pluralStringResource(@PluralsRes id: Int, count: Int): String {
    val resources = resources()
    return resources.getQuantityString(id, count)
}

/**
 * Load a plurals resource with provided format arguments.
 *
 * @param id the resource identifier
 * @param count the count
 * @param formatArgs arguments used in the format string
 * @return the pluralized string data associated with the resource
 */
@Composable
@ReadOnlyComposable
fun pluralStringResource(@PluralsRes id: Int, count: Int, vararg formatArgs: Any): String {
    val resources = resources()
    return resources.getQuantityString(id, count, *formatArgs)
}
作用方法
stringResource(@StringRes id: Int)
获取xml指定id字符串资源
stringResource(@StringRes id: Int, vararg formatArgs: Any)
获取xml指定id字符串资源,且格式化占位符号
stringArrayResource(@ArrayRes id: Int)
获取xml指定id字符串资源数组,返回是数组
<string-array name="xxx"...
pluralStringResource(@PluralsRes id: Int, count: Int)
根据数字的不同自动选择不同的字符串显示,特别是单复数。
特别是不同国家的语言对应不同的单复数。
pluralStringResource(@PluralsRes id: Int, count: Int, vararg formatArgs: Any)

根据数字的不同自动选择不同的字符串显示,特别是单复数。
特别是不同国家的语言对应不同的单复数。

 @Composable
    fun showXMLString(){
        Text(text = stringResource(id = R.string.app_name))
    }

文字颜色
color属性,但是是Color对象,暂时没看到支持resource的 得转换,估计也是md设计的原因 希望使用CompositionLocal来嫁接,其内置了很多常用色

  @Composable
    fun showTextColor(){
        Text(text = stringResource(id = R.string.app_name), color = Color.Yellow)
    }

文字大小


fontSize:UnitType类型

UnitType 支持sp 和em,app一般用sp,em 网页用得多,估计是为跨平台考虑,kotlin在数字上的拓展转化单位

 @Composable
    fun showTextSize(){
        Text(text = stringResource(id = R.string.app_name), fontSize =30.sp )
    }

文字粗细
fontWeight属性
类型是FontWeight,已经提前预置了很多static常量,当然也可以自己new,常用的

FontWeight.Bold
FontWeight.Medium

FontWeight.Normal

class FontWeight(val weight: Int) : Comparable<FontWeight> {

    companion object {
        /** [Thin] */
        @Stable
        val W100 = FontWeight(100)
        /** [ExtraLight] */
        @Stable
        val W200 = FontWeight(200)
        /** [Light] */
        @Stable
        val W300 = FontWeight(300)
        /** [Normal] / regular / plain */
        @Stable
        val W400 = FontWeight(400)
        /** [Medium] */
        @Stable
        val W500 = FontWeight(500)
        /** [SemiBold] */
        @Stable
        val W600 = FontWeight(600)
        /** [Bold] */
        @Stable
        val W700 = FontWeight(700)
        /** [ExtraBold] */
        @Stable
        val W800 = FontWeight(800)
        /** [Black] */
        @Stable
        val W900 = FontWeight(900)

        /** Alias for [W100] */
        @Stable
        val Thin = W100
        /** Alias for [W200] */
        @Stable
        val ExtraLight = W200
        /** Alias for [W300] */
        @Stable
        val Light = W300
        /** The default font weight - alias for [W400] */
        @Stable
        val Normal = W400
        /** Alias for [W500] */
        @Stable
        val Medium = W500
        /** Alias for [W600] */
        @Stable
        val SemiBold = W600
        /**
         * A commonly used font weight that is heavier than normal - alias for [W700]
         */
        @Stable
        val Bold = W700
        /** Alias for [W800] */
        @Stable
        val ExtraBold = W800
        /** Alias for [W900] */
        @Stable
        val Black = W900

        /** A list of all the font weights. */
        internal val values: List<FontWeight> = listOf(
            W100,
            W200,
            W300,
            W400,
            W500,
            W600,
            W700,
            W800,
            W900
        )
    }

    init {
        require(weight in 1..1000) {
            "Font weight can be in range [1, 1000]. Current value: $weight"
        }
    }

}
    @Composable
    fun showFontWeight(){
        Text(text = stringResource(id = R.string.app_name), fontWeight = FontWeight.Bold )
    }

文字对齐方式


textAlign属性,类型TextAlign对象,固定五6个常量对象

文字居中实例

  @Composable
    fun showTextAlign(){
        Text(text = "textAlign", textAlign = TextAlign.Center, modifier = Modifier.width(150.dp).background(Color.Blue))
    }


 

文字阴影

文字阴影没有一级属性,估计也是不常用,放在了style里面,style的类型是TextStyle,其实所有控制样式的一级属性最后都会merge到TextStyle对象里面,所以能通过一级属性控制的 也基本能通过TextStyle来控制

  @Composable
    fun showTextShadow(){
        Text(text = "textShadow",
            style = TextStyle(shadow = Shadow(color = Color.Gray,
            offset = Offset(10.0f,10.0f),
            blurRadius=3f)))
    }

文字字体
fontFamily属性,内置了6种字体

 @Composable
    fun showFontFamily(){
        Column(modifier = Modifier.padding(10.dp)) {
            Text(text = "FontFamily", fontFamily = FontFamily.Serif)
            Text(text = "FontFamily", fontFamily = FontFamily.SansSerif)
        }
    }

您可以使用 fontFamily 属性来处理 res/font 文件夹中定义的自定义字体和字型:

font 文件夹的图示" class="l10n-absolute-url-src screenshot" l10n-attrs-original-order="src,alt,width,class" src="https://developer.android.com/static/images/jetpack/compose/text-font-folder.png" width="400" />

此示例展示了如何根据这些字体文件以及使用 Font 函数定义 fontFamily

val firaSansFamily = FontFamily(
        Font(R.font.firasans_light, FontWeight.Light),
        Font(R.font.firasans_regular, FontWeight.Normal),
        Font(R.font.firasans_italic, FontWeight.Normal, FontStyle.Italic),
        Font(R.font.firasans_medium, FontWeight.Medium),
        Font(R.font.firasans_bold, FontWeight.Bold)
)

富文本样式


AnnotatedString类型,类型Android spanString,ios attributeString

通过spanStyle 来可以控制文字样式 字重 颜色,背景色等等

 @Composable
    fun MultipleStylesInText() {
        Text(
            buildAnnotatedString {
                withStyle(style = SpanStyle(color = Color.Blue)) {
                    append("H")
                }
                append("ello ")

                withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, color = Color.Red)) {
                    append("W")
                }
                append("orld")
            }
        )
    }

还可以设置段落样式,如下设置段落间距

@Composable
    fun ParagraphStyleDemo() {
        Text(
            buildAnnotatedString {
                withStyle(style = ParagraphStyle(lineHeight = 30.sp)) {
                    withStyle(style = SpanStyle(color = Color.Blue)) {
                        append("Hello\n")
                    }
                    withStyle(
                        style = SpanStyle(
                            fontWeight = FontWeight.Bold,
                            color = Color.Red
                        )
                    ) {
                        append("World\n")
                    }
                    append("Compose")
                }
            }
        )
    }

行数限制


maxLines,android 开发用得比较常见,不多说,看效果
 

 @Composable
    fun showMaxLine(){
        Box(modifier = Modifier.width(100.dp)) {
            Text("床前明月光,疑是地上双,举头望明月,低头思故乡", maxLines = 2, modifier = Modifier
                .padding(15.dp)
                .background(Color.Gray))
        }
    }

文字溢出

用于控制文字截断得时候表现形式,如尾部三个点 

相比于Android 还是特别少

   Text("床前明月光,疑是地上双,举头望明月,低头思故乡",
                maxLines = 2,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier
                .padding(15.dp)
                .background(Color.Gray))

文字选中


compose 需要套一个SelectionContainer才能实现长按划选文字
 

    @Composable
    fun showSelectableText() {
        SelectionContainer {
            Text("支持划选的文字")
        }
    }

而且还支持多个Text组件实现划选

  @Composable
    fun showMutiSelectableText() {
        SelectionContainer(modifier = Modifier.padding(10.dp)) {
            Column {
                Text("支持划选的文字第一个")
                Text("支持划选的文字第二个")
                Text("支持划选的文字第三个")
            }
        }
    }

当然也支持局部屏蔽 不让划选

   @Composable
    fun showMutiSelectableText() {
        SelectionContainer(modifier = Modifier.padding(10.dp)) {
            Column {
                Text("支持划选的文字第一个")
                DisableSelection {
                    Text("支持划选的文字第二个")
                }
                Text("支持划选的文字第三个")
            }
        }
    }


点击文字的位置


ClickableText可以获取点击文字的位置

@Composable
    fun showClickableText(){
        ClickableText(text = AnnotatedString("这个文字支持点击位置获取"), onClick ={ offset->
            println("===========>点击位置${offset}");
            Toast.makeText(this,"点击未知${offset}",Toast.LENGTH_SHORT);
        })
    }

所有实例demo地址

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/986975.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

如何挑选低值易耗品管理系统?优化企业管理效率与成本控制

在现代企业管理中&#xff0c;低值易耗品的管理是一个容易被忽视但却十分重要的环节。低值易耗品包括办公用品、耗材、工具等&#xff0c;它们虽然单价不高&#xff0c;但数量庞大且频繁使用&#xff0c;对企业的日常运营和成本控制有着重要影响。为了提高管理效率、降低成本&a…

Linux与shell命令行学习

文章目录 走进shell基本的bash shell命令2.1 遍历目录 cd2.2 查看文件和目录列表 ls2.3 创建文件 touch2.4 复制文件 cp2.5 自动补全 tab2.6 链接文件 ln2.7 文件重命名 mv2.8 删除文件 rm2.9 创建目录 mkdir2.10 删除目录 rmdir2.11 查看文件类型 file2.12 查看整个文件 cat、…

flume1.11.0安装部署

1、准备安装包apache-flume-1.11.0-bin.tar.gz&#xff1b; 上传&#xff1b; 2、安装flume-1.11.0&#xff1b; 解压&#xff1b; tar -zxvf apache-flume-1.11.0-bin.tar.gz -C /opt/server 进入conf目录&#xff0c;修改flume-env.sh&#xff0c;配置JAVA_HOME&#xff1b…

docker 生成镜像的几个问题

docker 生成镜像的几个问题 根据jdk8.tar.gz 打包Jdk8 镜像失败运行镜像报错差不多是网络ip错误,在网上说重启docker即可解决运行mysql5.7.25 镜像失败向daemon.json文件添加内容导致docker重启失败docker run 命令常用参数根据jdk8.tar.gz 打包Jdk8 镜像失败 首选做准备工作…

有向图和无向图的表示方式(邻接矩阵,邻接表)

目录 一.邻接矩阵 1.无向图​编辑 2.有向图 补充&#xff1a;网&#xff08;有权图&#xff09;的邻接矩阵表示法 二.邻接表 1.无向图 2.有向图 三.邻接矩阵与邻接表的关系 一.邻接矩阵 1.无向图 &#xff08;1&#xff09;对角线上是每一个顶点与自身之间的关系&…

智慧能源方案:TSINGSEE青犀AI算法中台在能源行业的应用

一、方案背景 互联网、物联网、人工智能等新一代信息技术引领新一轮产业革命&#xff0c;加快能源革命步伐。尤其是随着人工智能技术的不断发展&#xff0c;AI智能检测与识别技术在能源行业的应用也越来越广泛。与此同时&#xff0c;国家出台多项政策&#xff0c;将智慧能源纳…

【HTML5高级第三篇】drag拖拽、音频视频、defer/async属性、dialog应用

文章目录 一、拖拽事件1.1 拖拽事件1.2 案例&#xff1a;拖拽丢弃图片 二、音频和视频三、defer 与 async 属性3.1 概述3.2 示例一&#xff1a;3.3 示例二&#xff1a; 四、dialog 元素 一、拖拽事件 原生JavaScipt案例合集 JavaScript DOM基础 JavaScript 基础到高级 Canvas…

LabVIEW利用局部放电分析高压电气设备状态诊断

LabVIEW利用局部放电分析高压电气设备状态诊断 目前&#xff0c;高压电气设备状态的监控系统解决了早期故障检测的问题。局部放电起源于电力电气装置的绝缘。局部放电会导致绝缘层逐渐磨损和加速老化&#xff0c;因此可能导致绝缘完全击穿。因此&#xff0c;局部放电检测及其特…

gitLab(git)误提交命令

1.先使用下面命令查看一下分支上已提交的信息 git log 2.回退到之前的版本 git reset —hard 你要删除的提交哈希码&#xff08;一般是离这个命令最近的一串数字&#xff09; 3.覆盖掉远端的版本信息&#xff0c;使远端的仓库也回退到相应的版本 注意&#xff1a;切换到你提…

安装K8s基础环境软件(二)

所有节点执行 1、安装docker sudo yum install -y yum-utils sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.reposudo yum install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin systemctl…

解决报错之org.aspectj.lang不存在

一、IDEA在使用时&#xff0c;可能会遇到maven依赖包明明存在&#xff0c;但是build或者启动时&#xff0c;报找不存在。 解决办法&#xff1a;第一时间检查Setting->Maven-Runner红圈中的√有没有选上。 二、有时候&#xff0c;明明依赖包存在&#xff0c;但是Maven页签中…

SI3262 低功耗 SOC +13.56mhz刷卡+触摸三合一芯片,适用于智能锁方案

Si3262 是一款高度集成的低功耗 SOC 芯片&#xff0c;其集成了基于 RISC-V 核的低功耗MCU 和工作在 13.56MHz 的非接触式读写器模块。 MCU 模块具有低功耗、Low Pin Count、宽电压工作范围&#xff0c;集成了13/14/15/16 位精度的 ADC、LVD、UART、SPI、I2C、TIMER、WUP、IWDG、…

【FAQ】安防视频监控/视频汇聚平台EasyCVR服务重启,海康SDK设备无法上线的原因排查

TSINGSEE青犀视频监控汇聚平台EasyCVR可拓展性强、视频能力灵活、部署轻快&#xff0c;可支持的主流标准协议有国标GB28181、RTSP/Onvif、RTMP等&#xff0c;以及支持厂家私有协议与SDK接入&#xff0c;包括海康Ehome、海大宇等设备的SDK等。旭帆科技平台既具备传统安防视频监控…

将目标检测项目移植到linux上出现OSERROR

在windows上运行项目正常&#xff0c;但是在centos9上运行出现找到资源&#xff0c;第一次遇到这个问题&#xff0c;通过代码回找&#xff0c;一步一步发现&#xff0c;读取数据没问题&#xff0c;但是在预测的时候无法读取&#xff0c;查到的资料 说明显示字体问题&#xff0c…

Maven中导入jQuery,前端页面中引用jQuery

第一步pom文件中&#xff0c;配置maven坐标。 第二步&#xff0c;在前端页面中引用jQuery 注&#xff1a;该前端页面需要在web根目录即webapp目录下。可认为在maven中导入jQuery后&#xff0c;jquery.min.js文件放在目录webapp/webjars/jquery/3.3.1下。

大模型扫盲之小白入门手记

本篇内容来自小米集团数据科学部负责人刘汉武老师的数据特训营笔记。不涉及深入的知识&#xff0c;仅在扫盲。 首先一个问题&#xff1a;大模型和大语言模型的区别是什么&#xff1f; 有人说大模型像是连接数据的星辰&#xff0c;能给我们提供前所未有的见解和洞察。现有的大模…

【精读Uboot】its文件语法

前面我们分析了SPL汇编的执行过程&#xff0c;在SPL之后就要进入另一个loader加载镜像了。在正式分析跳转流程之前&#xff0c;我们需要搞清楚在我们平时下载的imx-boot-xxx这个镜像是如何组成的。 在编译完Uboot、optee和ATF之后&#xff0c;会产生u-boot-spl.bin&#xff0c…

element-plus 踩的坑

原来node版本是16.17.0,装element-plus死活装不上&#xff0c;结果要把node版本升级到18以上&#xff0c;真坑呀&#xff0c;也没人告诉我要这么干

如何调用Zabbix API获取主机信息

自Zabbix 1.8版本被引进以后&#xff0c;Zabbix API开始扮演着越来越重要的角色&#xff0c;它可以为批量操作、第三方软件集成以及其他应用提供可编程接口。 在运维实践中&#xff0c;Zabbix API还有更多巧妙的应用。 面对规模庞大的监控设备&#xff0c;可能会出现某台机器发…

Python接口自动化测试 —— logging日志

logging模块的日志级别&#xff1a;日志级别一共有5个从低到高如下&#xff0c; 作用是在当你给python函数赋予日志器时&#xff0c; 需要自己标记日志级别&#xff08;后面会用到&#xff09; debug&#xff08;调试级别&#xff09;&#xff1a;严重程度最低级别&#xff0c…