Compose Android Snackbar实现Toast效果

Compose SnackbarHost实现Toast效果

  • 代码如下:
less 复制代码
@Composable
fun SnackbarHost(
    hostState: SnackbarHostState,
    modifier: Modifier = Modifier,
    snackbar: @Composable (SnackbarData) -> Unit = { Snackbar(it) }
)
  • SnackbarHostState()控制状态、messaage、时长
kotlin 复制代码
suspend fun showSnackbar(
    message: String,
    actionLabel: String? = null,
    withDismissAction: Boolean = false,
    duration: SnackbarDuration =
        if (actionLabel == null) SnackbarDuration.Short else SnackbarDuration.Indefinite
)
kotlin 复制代码
SnackbarDuration.Indefinite -> Long.MAX_VALUE
SnackbarDuration.Long -> 10000L
SnackbarDuration.Short -> 4000L
  • 为了实现居中效果引入Box,默认是顶部弹出

默认弹出方式效果

  • 实现代码:
ini 复制代码
Box {
    var hostState = SnackbarHostState()
    SnackbarHost(hostState = hostState, modifier = Modifier.align(Alignment.Center))
    LaunchedEffect(key1 = "Toast") {
        hostState.showSnackbar(message = "Hello $name!", duration = SnackbarDuration.Short)
    }
}

手动控制关闭弹出效果,一种是actionLabel文字按钮关闭,一种是withDismissAction=true时 icon 删除按钮取消'X'

  • 实现代码:
ini 复制代码
Box {
    var hostState = SnackbarHostState()
    SnackbarHost(hostState = hostState, modifier = Modifier.align(Alignment.Center))
    LaunchedEffect(key1 = "Toast") {
        hostState.showSnackbar(
            message = "Hello $name!",
            actionLabel = "确定",
            withDismissAction = true,
            duration = SnackbarDuration.Indefinite
        )
    }
}

也可以自定义方式绘制,实现SnackbarHostsnackbar

  • 实现代码:
ini 复制代码
Box {
    var hostState = SnackbarHostState()
    SnackbarHost(hostState = hostState, modifier = Modifier.align(Alignment.Center)) {

        Card(
            Modifier
                .fillMaxWidth()
                .wrapContentHeight()
                .padding(horizontal = 8.dp),
            shape = RoundedCornerShape(8.dp),
            colors = CardDefaults.cardColors(
                containerColor = Color(0xFF326C9C),
                contentColor = Color.White
            ),
            elevation = CardDefaults.cardElevation(defaultElevation = 12.dp)
        ) {
            Text(
                text = it.visuals.message,
                modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)
            )
        }
    }
    LaunchedEffect(key1 = "Toast", block = {
        hostState.showSnackbar(message = "Hello $name!", duration = SnackbarDuration.Short)
    })
}

自定义方式绘制,实现SnackbarHostsnackbar,也可以用来制作成功失败Toast

  1. 不带文字的
  • 实现代码:
ini 复制代码
Box {
  var hostState = SnackbarHostState()
  SnackbarHost(hostState = hostState, modifier = Modifier.align(Alignment.Center)) {

      Card(
          Modifier
              .size(96.dp),
          shape = RoundedCornerShape(8.dp),
          colors = CardDefaults.cardColors(
              containerColor = Color.DarkGray,
              contentColor = Color.White
          ),
          elevation = CardDefaults.cardElevation(defaultElevation = 12.dp)
      ) {
          Box(Modifier.fillMaxSize()) {
              Icon(
                  imageVector = Icons.Default.Done,
                  contentDescription = it.visuals.message,
                  modifier = Modifier
                      .align(
                          Alignment.Center
                      )
                      .scale(1.5f)
              )
          }

      }
  }
  LaunchedEffect(key1 = "Toast", block = {
      hostState.showSnackbar(message = "success", duration = SnackbarDuration.Long)
  })
}
  1. 带文字的
  • 实现代码:
ini 复制代码
Box {
    var hostState = SnackbarHostState()
    SnackbarHost(hostState = hostState, modifier = Modifier.align(Alignment.Center)) {

        Card(
            Modifier
                .defaultMinSize(minWidth = 96.dp, minHeight = 96.dp),
            shape = RoundedCornerShape(8.dp),
            colors = CardDefaults.cardColors(
                containerColor = Color.DarkGray,
                contentColor = Color.White
            ),
            elevation = CardDefaults.cardElevation(defaultElevation = 12.dp)
        ) {
            Icon(
                imageVector = Icons.Default.Done,
                contentDescription = it.visuals.message,
                modifier = Modifier
                    .align(
                        Alignment.CenterHorizontally
                    )
                    .scale(2.0f)
                    .padding(top = 16.dp)
            )
            Text(
                text = it.visuals.message, modifier = Modifier
                    .align(
                        Alignment.CenterHorizontally
                    )
                    .padding(bottom = 16.dp, top = 16.dp)
            )
        }
    }
    LaunchedEffect(key1 = "Toast", block = {
        hostState.showSnackbar(message = "成功提示", duration = SnackbarDuration.Long)
    })
}

自定义方式绘制,实现SnackbarHostsnackbar,用来制作loading

  • 通过hostState.currentSnackbarData?.dismiss()控制取消,实现代码:
ini 复制代码
Box {
      var hostState = SnackbarHostState()

      SnackbarHost(hostState = hostState, modifier = Modifier.align(Alignment.Center)) {
          Card(
              Modifier
                  .size(96.dp),
              shape = RoundedCornerShape(8.dp),
              colors = CardDefaults.cardColors(
                  containerColor = Color.DarkGray,
                  contentColor = Color.White
              ),
              elevation = CardDefaults.cardElevation(defaultElevation = 12.dp)
          ) {
              var isStop by remember {
                  mutableStateOf(false)
              }
              var progress = animateFloatAsState(
                  targetValue = if (isStop) 1f else 0f,
                  animationSpec = infiniteRepeatable(
                      animation = tween(1000, easing = LinearEasing),
                      repeatMode = RepeatMode.Restart
                  ),
                  label = "progress"
              )

              Box(Modifier.fillMaxSize()) {
                  CircularProgressIndicator(
                      progress = progress.value,
                      strokeWidth = 4.dp,
                      strokeCap = StrokeCap.Round,
                      trackColor = Color.Transparent,
                      color = Color.Yellow,
                      modifier = Modifier
                          .size(50.dp)
                          .align(
                              Alignment.Center
                          )
                          .rotate(360 * progress.value)
                  )
//                    Icon(
//                        imageVector = Icons.Default.Refresh,
//                        contentDescription = "progress",
//                        modifier = Modifier.scale(2.0f).rotate(360 * progress.value).align(Alignment.Center)
//                    )
              }
              LaunchedEffect(key1 = "progress", block = {
                  isStop = true
              })
          }
      }
      LaunchedEffect(key1 = "Toast", block = {
          hostState.showSnackbar(message = "成功提示", duration = SnackbarDuration.Indefinite)
      })
      LaunchedEffect(key1 = "dismiss", block = {
          delay(10000L)
          hostState.currentSnackbarData?.dismiss()
      })
  }
总结:有Snackbar特性,也具备Toast功能,复杂Toast也能扩展
相关推荐
一笑的小酒馆23 分钟前
Android性能优化之截屏时黑屏卡顿问题
android
懒人村杂货铺3 小时前
Android BLE 扫描完整实战
android
TeleostNaCl5 小时前
如何安装 Google 通用的驱动以便使用 ADB 和 Fastboot 调试(Bootloader)设备
android·经验分享·adb·android studio·android-studio·android runtime
fatiaozhang95276 小时前
中国移动浪潮云电脑CD1000-系统全分区备份包-可瑞芯微工具刷机-可救砖
android·网络·电脑·电视盒子·刷机固件·机顶盒刷机
2501_915918417 小时前
iOS 开发全流程实战 基于 uni-app 的 iOS 应用开发、打包、测试与上架流程详解
android·ios·小程序·https·uni-app·iphone·webview
lichong9517 小时前
【混合开发】vue+Android、iPhone、鸿蒙、win、macOS、Linux之dist打包发布在Android工程asserts里
android·vue.js·iphone
Android出海7 小时前
Android 15重磅升级:16KB内存页机制详解与适配指南
android·人工智能·新媒体运营·产品运营·内容运营
一只修仙的猿7 小时前
毕业三年后,我离职了
android·面试
编程乐学8 小时前
安卓非原创--基于Android Studio 实现的新闻App
android·ide·android studio·移动端开发·安卓大作业·新闻app
雅雅姐9 小时前
Android14 init.rc中on boot阶段操作4
android