Android Compose 九:interactionSource 的使用

news2024/10/7 2:31:46

先上官方文档

InteractionSource
InteractionSource represents a stream of Interactions corresponding to events emitted by a component. These Interactions can be used to change how components appear in different states, such as when a component is pressed or dragged.
翻译
InteractionSource表示与组件发出的事件相对应的交互流。这些交互可用于更改组件在不同状态下的显示方式,例如按下或拖动组件时。

也就是说它应该是用来记录不同的交互状态
官方示例简化

val interactionSource = remember { MutableInteractionSource() }

//拖拽
val draggable = Modifier.draggable(
    interactionSource = interactionSource,
    orientation = Orientation.Horizontal,
    state = rememberDraggableState { /* update some business state here */ }
)

//点击
val clickable = Modifier.clickable(
    interactionSource = interactionSource,
    indication = LocalIndication.current
) { /* update some business state here */ }

//状态值变化结果
val isDragged by interactionSource.collectIsDraggedAsState()
val isPressed by interactionSource.collectIsPressedAsState()

//定义变化后的 text 和 color  下方Box 中 border使用了color    Text 使用了text
val (text, color) = when {
    isDragged && isPressed -> "Dragged and pressed" to Color.Red
    isDragged -> "Dragged" to Color.Green
    isPressed -> "Pressed" to Color.Blue
    // Default / baseline state
    else -> "Drag me horizontally, or press me!" to Color.Black
}

Box(
    Modifier
        .fillMaxSize()
        .wrapContentSize()
        .size(width = 240.dp, height = 80.dp)
) {
    Box(
        Modifier
            .fillMaxSize()
            .then(clickable)
            .then(draggable)
            .border(BorderStroke(3.dp, color))
            .padding(3.dp)
    ) {
        Text(
            text, style = LocalTextStyle.current.copy(textAlign = TextAlign.Center),
            modifier = Modifier.fillMaxSize().wrapContentSize()
        )
    }
}

将以上代码放入项目运行效果

  • 按下时 文字变化 边框边蓝
  • 拖拽时 文字变化 边框变绿
    请添加图片描述

官方示例2
以下是省略代码

 val interactions = remember { mutableStateListOf<Interaction>() }  //创建了个 集合
//用来记录 交互事件    添加或从集合中移除
 LaunchedEffect(interactionSource) {
        interactionSource.interactions.collect { interaction ->
            when (interaction) {
                is PressInteraction.Press -> interactions.add(interaction)
                is PressInteraction.Release -> interactions.remove(interaction.press)
                is PressInteraction.Cancel -> interactions.remove(interaction.press)
                is DragInteraction.Start -> interactions.add(interaction)
                is DragInteraction.Stop -> interactions.remove(interaction.start)
                is DragInteraction.Cancel -> interactions.remove(interaction.start)
            }
        }
    }

//集合状态变化 文字变化
  val text = when (interactions.lastOrNull()) {
        is DragInteraction.Start -> "Dragged"
        is PressInteraction.Press -> "Pressed"
        else -> "No state"
    }

//判断集合中 交互状态  显示不同的效果
 val pressed = interactions.any { it is PressInteraction.Press }
                Text(
                    text = if (pressed) "Pressed" else "Not pressed",
                    style = LocalTextStyle.current.copy(textAlign = TextAlign.Center),
                    modifier = Modifier.fillMaxSize().wrapContentSize()
                )
val dragged = interactions.any { it is DragInteraction.Start }
                Text(
                    text = if (dragged) "Dragged" else "Not dragged",
                    style = LocalTextStyle.current.copy(textAlign = TextAlign.Center),
                    modifier = Modifier.fillMaxSize().wrapContentSize()
                )

效果
请添加图片描述

使用

前面我们玩过的
TextField
Button
Switch
等组件 都有 interactionSource 属性
并且
Modifier.indication(
interactionSource = interactionSource,
indication = LocalIndication.current
)
也可以设置interactionSource

下面我们就简单玩玩它

实现输入框获取到焦点时 提示文字的改变
  • collectIsDraggedAsState 拖拽交互
  • collectIsFocusedAsState 焦点交互
  • collectIsHoveredAsState 悬停交互
  • collectIsPressedAsState 点击交互

创建两个TextField 可以用来切换焦点
直接上代码吧

   val inPut = remember {
        mutableStateOf("")
    }

    val interactionSource = remember { MutableInteractionSource() }

    //获取到当前焦点状态
    val isFocused by interactionSource.collectIsFocusedAsState()

    Column(modifier = Modifier.padding(10.dp)) {
        TextField(
            value = inPut.value,
            onValueChange ={
                inPut.value = it
            },
            modifier = Modifier
                .fillMaxWidth()
                .height(50.dp),
            shape = CircleShape,
            colors = TextFieldDefaults.textFieldColors(
                focusedIndicatorColor = Color.Transparent,
                disabledIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent,
            ),
            placeholder = {
                Text(text = "${if(isFocused)"请输入内容" else "这是一个提示语"}")
            },
            interactionSource = interactionSource,
        )

        Spacer(modifier = Modifier.height(20.dp))

        TextField(
            value = inPut.value,
            onValueChange ={
                inPut.value = it
            },
            modifier = Modifier
                .fillMaxWidth()
                .height(50.dp),
            shape = CircleShape,
            colors = TextFieldDefaults.textFieldColors(
                focusedIndicatorColor = Color.Transparent,
                disabledIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent,
            ),
            placeholder = {
                Text(text = "这是一个提示语")
            },
        )
    }

效果 上边的TextField 获取和失去焦点时,文字改变
请添加图片描述
更多的用法一般是
当TextField 获取到焦点时边框或者背景变化 用以表示我们选中了该输入框
于是 我们包一层


@ExperimentalMaterial3Api
@Composable
fun MyTextField(
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier,
    placeholder: @Composable (() -> Unit)? = null,
) {
    val interactionSource = remember { MutableInteractionSource() }
    //获取到当前焦点状态
    val isFocused by interactionSource.collectIsFocusedAsState()

    val color = when{
        isFocused -> Color.Red
        else -> Color.Black
    }

    TextField(
        value = value,
        onValueChange = onValueChange,
        modifier = modifier.border(3.dp,color, shape = CircleShape),
        shape = CircleShape,
        colors = TextFieldDefaults.textFieldColors(
            focusedIndicatorColor = Color.Transparent,
            disabledIndicatorColor = Color.Transparent,
            unfocusedIndicatorColor = Color.Transparent,
        ),
        placeholder = placeholder,
        interactionSource = interactionSource,
    )

}

然后使用

   val inPut = remember {
        mutableStateOf("")
    }

    Column(modifier = Modifier.padding(10.dp)) {
        MyTextField(
            value = inPut.value,
            onValueChange ={
                inPut.value = it
            },
            modifier = Modifier
                .fillMaxWidth()
                .height(50.dp),
            placeholder = {
                Text(text = "这是一个提示语")
            }
        )

        Spacer(modifier = Modifier.height(20.dp))

        MyTextField(
            value = inPut.value,
            onValueChange ={
                inPut.value = it
            },
            modifier = Modifier
                .fillMaxWidth()
                .height(50.dp),
            placeholder = {
                Text(text = "这是一个提示语")
            }
        )
    }

效果如下
请添加图片描述

那么问题来了,你们叫它什么名字呢 状态选择器么

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

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

相关文章

WordPress安装memcached提升网站速度

本教程使用环境为宝塔 第一步、服务器端安装memcached扩展 在网站使用的php上安装memcached扩展 第二步&#xff1a;在 WordPress 网站后台中&#xff0c;安装插件「Memcached Is Your Friend」 安装完成后启用该插件&#xff0c;在左侧工具-中点击Memcached 查看是否提示“U…

《拯救大学生课设不挂科第四期之蓝桥杯是什么?我是否要参加蓝桥杯?选择何种语言?如何科学备赛?方法思维教程》【官方笔记】

背景&#xff1a; 有些同学在大一或者大二可能会被老师建议参加蓝桥杯&#xff0c;本视频和文章主要是以一个过来人的身份来给与大家一些思路。 比如蓝桥杯是什么&#xff1f;我是否要参加蓝桥杯&#xff1f;参加蓝桥杯该选择何种语言&#xff1f;如何科学备赛&#xff1f;等…

webpack5生产模式

生产模式 生产模式准备 开发模式和生产模式有不同的 配置文件 2修改webpack.prod.js文件修改webpack.dev.js文件 修改webpack.dev.js文件 1》修改输出路径为undefined 2》将绝对路径进行修改&#xff0c;进行回退 此时文件的执行命令为 修改webpack.prod.js文件 1》修改绝…

跨平台之用VisualStudio开发APK嵌入OpenCV(三)

本篇将包含以下内容&#xff1a; 1.使用 Visual Studio 2019 开发一个 Android 的 App 2.导入前篇 C 编译好的 so 动态库 3.一些入门必须的其它设置 作为入门&#xff0c;我们直接使用真机进行调试&#xff0c;一方面运行速度远高于模拟器&#xff0c;另一方面模拟器使用的…

2024年【危险化学品经营单位安全管理人员】考试及危险化学品经营单位安全管理人员考试资料

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 危险化学品经营单位安全管理人员考试考前必练&#xff01;安全生产模拟考试一点通每个月更新危险化学品经营单位安全管理人员考试资料题目及答案&#xff01;多做几遍&#xff0c;其实通过危险化学品经营单位安全管理…

Zoho Campaigns邮件营销怎么发邮件?

Zoho Campaigns&#xff0c;作为业界领先的邮件营销平台&#xff0c;以其强大的功能、用户友好的界面以及深度的分析能力&#xff0c;为企业提供了一站式的邮件营销解决方案&#xff0c;助力企业高效地触达目标受众&#xff0c;构建并巩固庞大的客户基础。云衔科技为企业提供Zo…

电量计量芯片HLW8110的前端电路设计与误差分析校正.pdf 下载

电量计量芯片HLW8110的前端电路设计与误差分析校正.pdf 下载地址&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1vlCtC3LGFMzYpSUUDY-tEg 提取码&#xff1a;8110

用Prometheus全面监控MySQL服务:一篇文章搞定

简介 在现代应用中&#xff0c;MySQL数据库的性能和稳定性对业务至关重要。有效的监控可以帮助预防问题并优化性能。Prometheus作为一款强大的开源监控系统&#xff0c;结合Grafana的可视化能力&#xff0c;可以提供全面的MySQL监控方案。 设置Prometheus 安装Prometheus 使…

深度学习面试问题总结(21)| 模型优化

本文给大家带来的百面算法工程师是深度学习模型优化面试总结&#xff0c;文章内总结了常见的提问问题&#xff0c;旨在为广大学子模拟出更贴合实际的面试问答场景。在这篇文章中&#xff0c;我们还将介绍一些常见的深度学习面试问题&#xff0c;并提供参考的回答及其理论基础&a…

ic基础|时钟篇05:芯片中buffer到底是干嘛的?一文带你了解buffer的作用

大家好&#xff0c;我是数字小熊饼干&#xff0c;一个练习时长两年半的ic打工人。我在两年前通过自学跨行社招加入了IC行业。现在我打算将这两年的工作经验和当初面试时最常问的一些问题进行总结&#xff0c;并通过汇总成文章的形式进行输出&#xff0c;相信无论你是在职的还是…

leecode 637 二叉树的层平均值

leetcode 二叉树相关-层序遍历专题 二叉树的层序遍历一般来说&#xff0c;我们是利用队列来实现的&#xff0c;先把根节点入队&#xff0c;然后在出队后将其对应的子节点入队&#xff0c;然后往复此种操作。相比于二叉树的遍历递归&#xff0c;层序遍历比较简单&#xff0c;有…

2024年5月26日 (周日) 叶子游戏新闻

资深开发者&#xff1a;3A游戏当前处于一种尴尬的中间地带游戏行业整体&#xff0c;尤其是3A游戏正处于艰难时期。尽管2023年3A游戏佳作频出&#xff0c;广受好评&#xff0c;但居高不下的游戏开发成本&#xff08;传闻《漫威蜘蛛侠2》的制作成本高达3亿美元&#xff09;正严重…

WEB攻防【1】——ASP应用/HTTP.SYS/短文件/文件解析/Access注入/数据库泄漏

ASP&#xff1a;常见漏洞&#xff1a;本文所写这些 ASPX&#xff1a;未授权访问、报错爆路径、反编译 PHP&#xff1a;弱类型对比、mdb绕过、正则绕过&#xff08;CTF考得多&#xff09; JAVA&#xff1a;反序列化漏洞 Python&#xff1a;SSTI、字符串、序列化 Javascript&…

微服务下认证授权框架的探讨

前言 市面上关于认证授权的框架已经比较丰富了,大都是关于单体应用的认证授权,在分布式架构下,使用比较多的方案是--<应用网关>,网关里集中认证,将认证通过的请求再转发给代理的服务,这种中心化的方式并不适用于微服务,这里讨论另一种方案--<认证中心>,利用jwt去中…

elementui中 表格使用树形数据且固定一列时展开子集移入时背景色不全问题(父级和子级所展示的字段是不一样的时候)

原来的效果 修改后实现效果 解决- 需要修改elementui的依赖包中lib/element-ui.common.js中的源码 将js中此处代码改完下面的代码 watch: {// dont trigger getter of currentRow in getCellClass. see https://jsfiddle.net/oe2b4hqt/// update DOM manually. see https:/…

【单片机】STM32F070F6P6 开发指南(一)STM32建立HAL工程

文章目录 一、基础入门二、工程初步建立三、HSE 和 LSE 时钟源设置四、时钟系统&#xff08;时钟树&#xff09;配置五、GPIO 功能引脚配置六、配置 Debug 选项七、生成工程源码八、生成工程源码九、用户程序下载 一、基础入门 f0 pack下载&#xff1a; https://www.keil.arm…

关于XtremIO 全闪存储维护的一些坑(建议)

XtremIO 是EMC过去主推的一款全闪存储系统&#xff0c;号称性能小怪兽&#xff0c;对付那些对于性能要求极高的业务场景是比较合适的&#xff0c;先后推出了1代和2代产品&#xff0c;目前这个产品好像未来的演进到了PowerStor或者PowerMax全闪&#xff0c;应该不独立发展这个产…

Leetcode260

260. 只出现一次的数字 III - 力扣&#xff08;LeetCode&#xff09; class Solution {public int[] singleNumber(int[] nums) {//通过异或操作,使得最终结果为两个只出现一次的元素的异或值int filterResult 0;for(int num:nums){filterResult^num;}//计算首个1(从右侧开始)…

[JDK工具-6] jmap java内存映射工具

文章目录 1. 介绍2. 主要选项3. 生成java堆转储快照 jmap -dump4. 显示堆详细信息 jmap -heap pid5. 显示堆中对象统计信息 jmap -histo pid jmap(Memory Map for Java) 1. 介绍 位置&#xff1a;jdk\bin 作用&#xff1a; jdk安装后会自带一些小工具&#xff0c;jmap命令(Mem…