Compose 简单组件

news2024/10/5 12:53:29

文章目录

  • Compose 简单组件
    • Text
      • Text属性
      • 使用
      • AnnotatedString
        • SpanStyle
        • ParagraphStyle
      • SelectionContainer 和 DisableSelection
      • ClickableText
    • TextField
      • TextField属性
      • 使用
      • OutlinedTextField
      • BasicTextField
      • KeyboardOptions 键盘属性
      • KeyboardActions IME动作
    • Button
      • Button属性
      • 使用
    • Image
      • Image属性
      • 使用
      • ContentScale 缩放比
      • alpha 图片透明度
      • colorFilter 图片着色
      • 加载网络图片
    • CircularProgressIndicator & LinearProgressIndicator
      • 圆形进度条
      • 条形进度条

Compose 简单组件

Text

Compose中的“TextView”。

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 // 样式配置,包含颜色、字体、行高等
)

使用

在这里插入图片描述

Column(modifier = Modifier.fillMaxSize()) {
    Text(
        "hello compose",
        color = Color.Red,
        fontSize = 16.sp,
        fontStyle = FontStyle.Italic,
        fontWeight = FontWeight.Bold
    )
    Text(
        stringResource(id = R.string.app_text),
        color = Color.Blue,
        fontFamily = FontFamily.Cursive
    )
    Text("下划线", textDecoration = TextDecoration.Underline)
    Text("贯穿线", textDecoration = TextDecoration.LineThrough)
    Text("猫和老鼠", textAlign = TextAlign.Center, modifier = Modifier.width(250.dp))
    Text(
        "床前明月光,疑似地上霜,举头望明月,低头思故乡", lineHeight = 35.sp, modifier = Modifier.width(250.dp)
    )
}

AnnotatedString

AnnotatedString 支持在同一组Text中设置不同的样式。

SpanStyle

SpanStyle 用于字符。

在这里插入图片描述

Text(buildAnnotatedString {
    withStyle(style = SpanStyle(color = Color.Blue, fontWeight = FontWeight.Bold)) {
        append("H")
    }
    append("ello")
    withStyle(style = SpanStyle(color = Color.Red, fontWeight = FontWeight.Bold)) {
        append("W")
    }
    append("orld")
})
ParagraphStyle

ParagraphStyle 用于整个段落。

在这里插入图片描述

Text(buildAnnotatedString {
    withStyle(style = ParagraphStyle(lineHeight = 30.sp)) {
        withStyle(style = SpanStyle(color = Color.Blue)) {
            append("Hello")
            append("\n")
        }
        withStyle(style = SpanStyle(color = Color.Red)) {
            append("World")
            append("\n")
        }
        append("Text")
    }
})

SelectionContainer 和 DisableSelection

  • SelectionContainer 用于文字选择。
  • DisableSelection 用于禁止文字选择。

在这里插入图片描述

SelectionContainer(modifier = Modifier.fillMaxSize()) {
    Column {
        Text("床前明月光")
        Text("疑是地下霜")
        DisableSelection {
            Text("hello")
            Text("world")
        }
        Text("举头望明月")
        Text("低头思故乡")
    }
}

ClickableText

  • ClickableText 用于可点击文本。
ClickableText(text = AnnotatedString("hello world"), 
              onClick = { offset ->
                         Log.e("TAG", "offset: ${offset}")  
                        }
             )

在Text中添加额外信息:

val annotatedString = buildAnnotatedString {
    append("点击")
    pushStringAnnotation(tag = "URL", annotation = "https://www.baidu.com/")
    withStyle(style = SpanStyle(color = Color.Red, fontWeight = FontWeight.Bold)) {
        append("Url")
    }
    pop()
}
    ClickableText(text = annotatedString, style = TextStyle(fontSize = 30.sp), onClick = { offset ->
        annotatedString.getStringAnnotations(tag = "URL", start = offset, end = offset)
            .firstOrNull()?.let { annotation -> Log.e("TAG", annotation.item) }
    })

TextField

Compose中的"EditText"。

TextField属性

@Composable
fun TextField(
    value: String,
    onValueChange: (String) -> Unit, // 监听输入变化
    modifier: Modifier = Modifier, // 修饰符
    enabled: Boolean = true, // 是否可点击
    readOnly: Boolean = false, // 是否只读
    textStyle: TextStyle = LocalTextStyle.current, // 文字样式
    label: @Composable (() -> Unit)? = null, // 定义label组件
    placeholder: @Composable (() -> Unit)? = null, // 定义placeholder组件
    leadingIcon: @Composable (() -> Unit)? = null, // 定义前置图标
    trailingIcon: @Composable (() -> Unit)? = null, // 定义后置图标
    isError: Boolean = false, // 是否提示错误
    visualTransformation: VisualTransformation = VisualTransformation.None, // 转换输入值
    keyboardOptions: KeyboardOptions = KeyboardOptions.Default, // 软键盘选项,类似于inputType
    keyboardActions: KeyboardActions = KeyboardActions(), // IME动作
    singleLine: Boolean = false, // 是否单行
    maxLines: Int = Int.MAX_VALUE, // 支持最大行数
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, // 交互流
    shape: Shape =
        MaterialTheme.shapes.small.copy(bottomEnd = ZeroCornerSize, bottomStart = ZeroCornerSize), // 输入框形状
    colors: TextFieldColors = TextFieldDefaults.textFieldColors() // 不同状态下颜色
)

使用

简单使用:

在这里插入图片描述

val text = remember { mutableStateOf("hello") }
TextField(value = text.value, onValueChange = { text.value = it }, label = { Text("标签") })

其他属性使用:

在这里插入图片描述

val text = remember { mutableStateOf("hello") }
TextField(
    value = text.value,
    onValueChange = { text.value = it },
    label = { Text("请输入") },
    maxLines = 2,
    textStyle = TextStyle(color = Color.Blue),
    modifier = Modifier.padding(20.dp)
)

OutlinedTextField

在这里插入图片描述

val text = remember { mutableStateOf("hello") }
OutlinedTextField(value = text.value, onValueChange = { text.value = it }, label = { Text("标签") })

BasicTextField

val text = remember { mutableStateOf("hello") }
BasicTextField(value = text.value, onValueChange = { text.value = it })

KeyboardOptions 键盘属性

class KeyboardOptions constructor(
    // 大写选项:
    // None 无大写,Characters 全部大写,Words 单词首字母大写,Sentences 句子首字母大写
    val capitalization: KeyboardCapitalization = KeyboardCapitalization.None, 
    // 是否开启自动更正
    val autoCorrect: Boolean = true,
    // 键盘类型:
    // Text 普通类型,Ascii ASCII字符类型,Number 数字类型,Phone 电话号码
    // Uri URI类型,Email 邮件地址类型,Password 密码类型,NumberPassword 数字密码类型
    val keyboardType: KeyboardType = KeyboardType.Text,
    // IME动作
    // Default 默认行为,None 不执行任何操作,默认为换行,Go 开始动作,Search 搜索动作
    // Send 发送动作,Previous 上一个,Next 下一步,Done 完成
    val imeAction: ImeAction = ImeAction.Default
) 
val text = remember { mutableStateOf("hello") }
TextField(
    value = text.value,
    onValueChange = { text.value = it },
    label = { Text("请输入") },
    maxLines = 2,
    textStyle = TextStyle(color = Color.Blue),
    modifier = Modifier.padding(20.dp),
    keyboardOptions = KeyboardOptions(
        capitalization = KeyboardCapitalization.Characters,
        keyboardType = KeyboardType.Email,
        autoCorrect = true,
        imeAction = ImeAction.Done
    )
)

KeyboardActions IME动作

val context = LocalContext.current
val text = remember { mutableStateOf("hello") }
TextField(
    value = text.value,
    onValueChange = { text.value = it },
    label = { Text("请输入") },
    maxLines = 2,
    textStyle = TextStyle(color = Color.Blue),
    modifier = Modifier.padding(20.dp),
    keyboardOptions = KeyboardOptions(
        capitalization = KeyboardCapitalization.Characters,
        keyboardType = KeyboardType.Email,
        autoCorrect = true,
        imeAction = ImeAction.Search
    ),
    keyboardActions = KeyboardActions(onSearch = {
        Toast.makeText(context, "${text.value} world", Toast.LENGTH_SHORT).show()
    })
)

Button

Compose中的”Button“。

Button属性

@Composable
fun Button(
    onClick: () -> Unit, // 点击事件
    modifier: Modifier = Modifier, // 修饰符
    enabled: Boolean = true, // 是否可点击
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, // 交互流
    elevation: ButtonElevation? = ButtonDefaults.elevation(), // 高度
    shape: Shape = MaterialTheme.shapes.small, // 按钮形状
    border: BorderStroke? = null, // 边框
    colors: ButtonColors = ButtonDefaults.buttonColors(), // 不同状态下颜色
    contentPadding: PaddingValues = ButtonDefaults.ContentPadding, // 内边距
    content: @Composable RowScope.() -> Unit // 内容
)

使用

简单使用:

在这里插入图片描述

Button(onClick = { }, shape = RoundedCornerShape(10.dp)) {
    Text("按钮")
}

使用colors属性:

colors就是用来设置按钮在不同状态下的颜色的。

在这里插入图片描述

Button(
    onClick = { },
    shape = RoundedCornerShape(10.dp),
    colors = ButtonDefaults.buttonColors(
        backgroundColor = Color.Red, // 背景颜色
        contentColor = Color.Green, // 内容颜色
        disabledBackgroundColor = Color.Blue, // 未启用时的背景颜色
        disabledContentColor = Color.Gray // 未启用时的内容颜色
    )
) {
    Text("按钮")
}

使用contentPadding属性:

contentPadding用于设置内容与容器间的距离。

在这里插入图片描述

Button(
    onClick = { },
    contentPadding = PaddingValues(20.dp, 10.dp)
) {
    Text("按钮")
}

Image

Compose中的”ImageView“。

Image属性

@Composable
fun Image(
    painter: Painter,
    contentDescription: String?, // 文字描述
    modifier: Modifier = Modifier, // 修饰符
    alignment: Alignment = Alignment.Center, // 对齐方式
    contentScale: ContentScale = ContentScale.Fit, // 图片缩放模式
    alpha: Float = DefaultAlpha, // 透明度
    colorFilter: ColorFilter? = null // 修改图片
)


@Composable
@NonRestartableComposable
fun Image(
    bitmap: ImageBitmap,
    contentDescription: String?,
    modifier: Modifier = Modifier,
    alignment: Alignment = Alignment.Center,
    contentScale: ContentScale = ContentScale.Fit,
    alpha: Float = DefaultAlpha,
    colorFilter: ColorFilter? = null,
    filterQuality: FilterQuality = DefaultFilterQuality
)

使用

简单使用:

在这里插入图片描述

Image(
    painter = painterResource(id = R.drawable.ic_launcher_background),
    contentDescription = "图片"
)

使用Bitmap:

val context = LocalContext.current
val path = "${context.cacheDir}${File.separator}a.jpg"
val bitmap = BitmapFactory.decodeFile(path)
Image(
    bitmap = bitmap.asImageBitmap(), contentDescription = null
)

ContentScale 缩放比

@Stable
interface ContentScale {
    // 计算缩放因子
    fun computeScaleFactor(srcSize: Size, dstSize: Size): ScaleFactor

    companion object {
        // 保持图片宽高比,使图片大于或等于目标尺寸
        @Stable
        val Crop 

        // 保持图片宽高比,使图片大于或等于目标尺寸
        @Stable
        val Fit 
        
        // 缩放图片并保持宽高比,使图片高度匹配目标尺寸
        @Stable
        val FillHeight 
        
        // 缩放图片并保持宽高比,使图片宽度匹配目标尺寸
        @Stable
        val FillWidth 
        
        // 如果图片大于目标,则缩放
        @Stable
        val Inside  

        // 不处理
        @Stable
        val None = FixedScale(1.0f)

        // 横向和纵向缩放填充目标尺寸
        @Stable
        val FillBounds
    }
}
Image(
    painter = painterResource(id = R.drawable.a),
    contentDescription = null,
    contentScale = ContentScale.Crop,
    modifier = Modifier.fillMaxSize(0.5F)
)

alpha 图片透明度

Image(
    painter = painterResource(id = R.drawable.a),
    contentDescription = null,
    alpha = 0.5F
)

colorFilter 图片着色

@Immutable
class ColorFilter internal constructor(internal val nativeColorFilter: NativeColorFilter) {
    companion object {
        // 使用颜色滤镜
        // 参数一:颜色值,参数二:混合模式
        @Stable
        fun tint(color: Color, blendMode: BlendMode = BlendMode.SrcIn): ColorFilter =
            actualTintColorFilter(color, blendMode)

        // 使用颜色矩阵,用于修改饱和度        
        @Stable
        fun colorMatrix(colorMatrix: ColorMatrix): ColorFilter =
            actualColorMatrixColorFilter(colorMatrix)

        // 模拟灯光效果
        @Stable
        fun lighting(multiply: Color, add: Color): ColorFilter =
            actualLightingColorFilter(multiply, add)
    }
}

加载网络图片

添加依赖库:

coil是一个图片加载库,完全使用Kotlin编写,使用了Kotlin的协程,图片网络请求方式默认为OkHttp。其特点如下:足够快速,它在内存、图片存储、图片采样、Bitmap重用、暂停/取消下载等细节方面都做了大幅优化。

 implementation "com.google.accompanist:accompanist-coil:0.15.0"

使用:

在这里插入图片描述

val painter = rememberImagePainter(
    data = "https://www.baidu.com/img/flexible/logo/pc/result@2.png",
    imageLoader = LocalImageLoader.current
)
Image(
    painter = painter,
    contentDescription = null,
    modifier = Modifier.border(
        1.dp,
        Color.Red,
        shape = RectangleShape
    )
)

CircularProgressIndicator & LinearProgressIndicator

Compose中的”ProgressBar“。

圆形进度条

简单使用:

在这里插入图片描述

CircularProgressIndicator()

使用属性:

在这里插入图片描述

CircularProgressIndicator(
    modifier = Modifier.size(100.dp),
    color = Color.Red,
    strokeWidth = 10.dp
)

设置进度:

在这里插入图片描述

CircularProgressIndicator(
    progress = 0.5F,
    modifier = Modifier.size(100.dp),
    color = Color.Red,
    strokeWidth = 10.dp
)

条形进度条

简单使用:

在这里插入图片描述

LinearProgressIndicator()

设置进度:

在这里插入图片描述

LinearProgressIndicator(
    progress = 0.5F,
    color = Color.Red,
    backgroundColor = Color.Blue
)

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

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

相关文章

【超级简单】vscode进入服务器的docker容器

前提 1、已经运行docker容器 2、已经用vscode链接服务器 在vscode中安装的插件 Dev Containers docker 在容器中安装的依赖 yum install openssh-server yum install openssh-clientsvscode进入服务器的docker容器 找到自己的容器,右键点击,找到…

网络安全可以免费学习吗?

当然可以!!! 这边每周都有免费的网络安全公开课!! 感兴趣的可以直接留言! 会有专门的人联系的 或者关注公众号:IT运维大本营,私信即可参加

研究表明,全球互联网流量竟有一半来自机器人

据Cyber News消息,Thales Imperva Bad Bot近期做了一份报告,显示在2023年有49.6%的互联网流量竟来自机器人,比上一年增长 2%,达到自2013年以来观察到的最高水平。 报告称,这一趋势正对企业组织产生负面影响&#xff0c…

鸿蒙原生应用元服务-访问控制(权限)开发等级和类型

一、权限等级说明 根据接口所涉数据的敏感程度或所涉能力的安全威胁影响,ATM模块定义了不同开放范围的权限等级来保护用户隐私。 应用APL等级说明 元能力权限等级APL(Ability Privilege Level)指的是应用的权限申请优先级的定义,…

MySQL Workbench下载安装、 MySQL Workbench使用

官方下载链接;MySQL :: Download MySQL Workbench 下载好懒人安装,也可自己选择目录 下面是使用: 连接数据库: 填写数据库连接信息: 基本操作部分: 数据导入导出: 导出/备份 导入: 生产er图…

基于springboot实现图书进销存管理系统项目【项目源码+论文说明】

基于springboot实现图书进销存管理系统演示 摘要 随着信息技术在管理上越来越深入而广泛的应用,管理信息系统的实施在技术上已逐步成熟。本文介绍了图书进销存管理系统的开发全过程。通过分析图书进销存管理系统管理的不足,创建了一个计算机管理图书进销…

第 6 章 URDF、Gazebo与Rviz综合应用(自学二刷笔记)

重要参考: 课程链接:https://www.bilibili.com/video/BV1Ci4y1L7ZZ 讲义链接:Introduction Autolabor-ROS机器人入门课程《ROS理论与实践》零基础教程 6.7.4 kinect信息仿真以及显示 通过 Gazebo 模拟kinect摄像头,并在 Rviz 中显示kinect摄像头数据…

守护脑积水宝宝,共筑健康未来

每个新生命的诞生,都承载着家庭的殷切期望与无尽的欢乐。然而,有些宝宝自诞生起便笼罩在健康的阴霾之下——脑积水。这是一种因脑脊液分泌过多或循环吸收障碍导致的疾病,其特征是颅内脑脊液量增加、脑室系统扩大或蛛网膜下腔扩大。脑脊液&…

【汇编语言实验九】

汇编语言实验九 在屏幕中间显示‘welcome to masm!’ assume cs:code,ds:datasgdatasg segmentdb welcome to masm! datasg endsstack segmentdw 0,0,0,0,0,0,0,0 stack endscode segment ;代码段start: nopmov cx,16mov si,0mov bx,0s: mov ax,datasgmov ds,axmov dh,02mov …

在wix和wordpress之间你应该选择哪一个?3件你需要知道的事

如果你最近需要制作网站,为了帮助您缩小选择范围并选择满足您独特需求的解决方案,我们比较了两个最大的名字:Wix和WordPress。 为了帮助您缩小选择范围并挑选出满足您独特需求的解决方案,我们将对两个比较受欢迎的自助建站系统——…

【Java基础学习】面向对象编程

开始时间: April 10, 2024 结束时间: April 16, 2024 阶段: Done 基础部分 类与对象的关系 类是抽象的,概念的,代表一类事物对象是具体的,实际的,代表一个具体事物(实例)类是对象的模板,对象…

在Linux操作系统中,修改文件目录权限常用的命令操作

修改文件的属主或者是属组 命令chown 用户名.用户组名,文件路径 如上图所示,使用命令 chown martin.caiwu /opt/test/1.txt 将文件1.txt的属主修改为martin 。 将文件1.txt的属组修改为caiwu 如上图所示,使用命令chown .jishu /opt/test/…

网络革新:ETU-LINK 100G AOC全系列产品驱动数字经济的加速发展

高效、稳定、高速的网络连接成为各行业发展的基石。之前的文章内容小编为大家介绍了ETU-LINK 100G DAC系列产品,本期文章我们来看看100G AOC产品,它在网络技术革新中又起着什么作用呢? 一、100G AOC全系列产品解析 100G QSFP28 AOC有源光缆 …

Android --- Activity

https://developer.android.com/guide/components/activities/intro-activities?hlzh-cn Activity 提供窗口,供应在其中多个界面。此窗口通常会填满屏幕,但也可能小于屏幕并浮动在其他窗口之上。 大多数应用包含多个屏幕,这意味着它们包含…

算法课程笔记——全排列

要最小 ventor用endl 递归方式#include <cstdio>#include <iostream>#include <algorithm>#include <string>using namespace std;const int MAXN 10;bool visit[MAXN];//判断某个元素是否被访问过char sequence[MAXN];//存放找到的全排列void GetPer…

2024年苹果审核4.3相关问题综述

苹果审核中的4.3问题是开发者关注的焦点之一&#xff0c;本文对此进行了综述&#xff0c;总结了不同情况下的处理方式和优化策略。 第一种4.3 该类问题常见于代码或UI的重复率过高&#xff0c;苹果会直接拒绝应用。开发者需注意避免此类情况的发生&#xff0c;特别是在更新应…

MongoDB 使用

1 引用依赖包 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency>2 配置文件配置mongodb资料 # MongoDB连接信息 spring.data.mongodb.host 192.168.23.…

03-JAVA设计模式-组合模式

组合模式 什么是组合模式 组合模式&#xff08;Composite Pattern&#xff09;允许你将对象组合成树形结构以表示“部分-整体”的层次结构&#xff0c;使得客户端以统一的方式处理单个对象和对象的组合。组合模式让你可以将对象组合成树形结构&#xff0c;并且能像单独对象一…

支持向量机模型pytorch

通过5个条件判定一件事情是否会发生&#xff0c;5个条件对这件事情是否发生的影响力不同&#xff0c;计算每个条件对这件事情发生的影响力多大&#xff0c;写一个支持向量机模型pytorch程序,最后打印5个条件分别的影响力。 示例一 支持向量机&#xff08;SVM&#xff09;是一种…

企业网盘搭建——LNMP

php包链接&#xff1a;https://pan.baidu.com/s/1RElYTQx320pN6452N_7t1Q?pwdp8gs 提取码&#xff1a;p8gs 网盘源码包链接&#xff1a;https://pan.baidu.com/s/1BaYqwruka1P6h5wBBrLiBw?pwdwrzo 提取码&#xff1a;wrzo 目录 一.手动部署 二.自动部署 一.手动部署 …