Compose 简单组件

文章目录

  • 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.mfbz.cn/a/551405.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Python 数据结构和算法实用指南(三)

原文:zh.annas-archive.org/md5/66ae3d5970b9b38c5ad770b42fec806d 译者:飞龙 协议:CC BY-NC-SA 4.0 第七章:哈希和符号表 我们之前已经看过数组和列表,其中项目按顺序存储并通过索引号访问。索引号对计算机来说很有效…

Docker+Uwsgi+Nginx部署Django项目保姆式教程

之前,我和大家分享了在docker中使用uwsgi部署django项目的教程。这次,为大家带来的是使用DockerUwsgiNginx部署Django项目。废话不多说,我们开干。 步骤1:使用命令创建一个django项目 我这里python版本使用的是3.9.x 首先&#…

有爱有乐有知识,还有《米小圈上学记》!

“读万卷书,不如行万里路”,说的是读再多的书,也比不上走过万水千山所得。可是又有几人能得尝山水之妙,大多被困于尘世中。我虽走过一些山水,但大多因生存困于一隅,不得随心而行。 然而,读书也…

nmon进行性能资源监控

一、前言 在工作中可能会遇到需要在压测的时候对Linux服务器进行性能资源监控的情况。这时可以用nmon来对服务器进行监控。 二、nmon的下载安装 1.查看系统信息 cat /etc/os-release 结果为 PRETTY_NAME"Debian GNU/Linux 12 (bookworm)"NAME"Debian GNU/…

不用Linux也可以的强大文本处理方法

不用Linux也可以的强大文本处理方法 标题党了,其实是论VIM的使用。 做生物信息分析最合适的还是Linux操作系统,所以生信宝典在最开始就推出了Linux学习系列,由浅入深的讲述了Linux学习中的关键点。 主要文章列举如下: Linux学…

代码随想录算法训练营DAY25|C++回溯算法Part.2|216. 组合总和II、17.电话号码的字母组合

文章目录 216. 组合总和II题意理解树形结构伪代码实现剪枝操作CPP代码实现 17.电话号码的字母组合解题思路树形结构伪代码实现隐藏回溯CPP代码 216. 组合总和II 力扣题目链接 文章讲解:216. 组合总和III 视频讲解:和组合问题有啥区别?回溯算法…

python复制文件夹内容

参考博客 https://blog.csdn.net/itfans123/article/details/133710731 案例1 import os import shutildef copy_folder(source_folder, destination_folder):# 创建目标文件夹os.makedirs(destination_folder, exist_okTrue)# 遍历源文件夹中的所有文件和文件夹for item in …

【简单讲解下如何用爬虫玩转石墨文档】

🎥博主:程序员不想YY啊 💫CSDN优质创作者,CSDN实力新星,CSDN博客专家 🤗点赞🎈收藏⭐再看💫养成习惯 ✨希望本文对您有所裨益,如有不足之处,欢迎在评论区提出…

力扣算法-回溯

递归 104.二叉树的最大深度 回溯 17.电话号码的字母组合 ①子集型回溯 78.子集 (1)选不选 (2)选哪个 131.分割回文串 (1593.拆分字符串使唯一子字符串的数目最大 也可以用这个思路解:从结果角度,分割字符串) ②组合型回溯…

【C++】哈希二

上篇博客我们写了解决哈希冲突的两种办法,不过我们写的都是针对整形的,而在实际情况下,要存入哈希表中的数据可以是string或自定义类型等等。那么我们就应该想一种办法去解决这里的问题。 比如说string,我们想到如何让string也转为…

代码随想录算法练习Day11:链表相交

题目:给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。 题目链接:160.链表相交 题目思路:定义两个指针,分别遍历两链表,如…

后端获取请求体Body,将请求体进行解密放回Request请求,并能通过@RequestBody获取

目前系统发送的post和put请求都是没有加密数据。客户需要将请求体加密。而系统已经基本开发完成,不可能一个一个去修改发送的请求。就需要在发送请求时候在拦截器中将body进行加密。并且在后端进行请求过滤解密,并且能通过RequestBody继续获取对象。 1.…

RuoYi-Cloud部署实战(手动部署)

RuoYi-Cloud部署实战 语雀 1. 若依源码和架构 RuoYi-Cloud: 🎉 基于Spring Boot、Spring Cloud & Alibaba的分布式微服务架构权限管理系统,同时提供了 Vue3 的版本 若依项目结构 带端口号的是需要启动的服务 com.ruoyi ├── ruoyi-ui …

各大厂都推出鸿蒙APP了,你就一定要学习一下鸿蒙APP测试了!

2023年8月,华为推出鸿蒙4.0,由于其广泛的用户基础和品牌传播力,在短短几个月的时间,使用鸿蒙4.0系统的设备就达到千万级别,并且在9月份发售Mate 6之后,还在装机量的增长更加迅猛。 基于此,11月…

德立电子授权世强先进代理分销,加速车规级磁性元器件产品拓展

为提供先进、可靠的磁性元件产品,世强先进(深圳)科技有限公司与惠州市德立电子有限公司(下称“德立电子”,英文名:DDY) 签署授权代理合作协议,旨在为汽车电子、工业、消费、通信、医…

Java GUI制作双人对打游戏(上)

文章目录 前言什么是Java GUI一、打开IDEA 新建一个Maven项目(后续可以打包、引入相关依赖也很容易)二、引入依赖三.绘制UI界面四.绘制JPanel面板总结 前言 什么是Java GUI Java UI,即Java用户界面,是指使用Java编程语言创建的图形用户界面&#xff08…

实现分布式锁

实现分布式锁的两个核心: 一、获取锁 1、获取锁线程互斥性 为了实现只有一个线程能继续执行业务代码,必须保证获取锁具有互斥性,即只有一个线程能获取到锁。 Redis中操作数据是单线程的,可以使用Redis提供的set nx ex命令获取锁。…

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

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

Ubuntu 22.04 安装 zabbix

Ubuntu 22.04 安装 zabbix 1,Install Zabbix repository2,安装Zabbix server,Web前端,agent3,安装mysql数据库3.1 创建初始数据库3.2 导入初始架构和数据,系统将提示您输入新创建的密码。3.3 在导入数据库架…

课题学习(二十一)----姿态更新的四元数算法推导

声明:本人水平有限,博客可能存在部分错误的地方,请广大读者谅解并向本人反馈错误。    最近需要使用AEKF对姿态进行结算,所以又对四元数进了深入的学习,本篇博客仅对四元数进行推导,后续会对基于四元数的…
最新文章