kotlin安卓开发【Jetpack Compose】:封装SnackBarUtil工具类方便使用

简介: GPT-4o 是一个非常智能的模型,比当前的通义千问最新版本在能力上有显著提升。作者让GPT开发一段代码,功能为在 Kotlin 中使用 Jetpack Compose 框架封装一个 Snackbar 工具类,方便调用



大模型返回的代码, 根本就没法用,本篇是一个 badcase。 实际上应该使用Toast,非常简单易用。Toast的具体使用,见文章最后



问题:

kotlin 开发安卓app, 使用Jetpack Compose框架。 帮我封装一个好用的util 工具类, 实现一行代码可以调用snackbar 显示一个简短的信息, 支持 错误类型, 警告类型, 消息类型, 成功类型, 不同的图标加上具体的同时信息一起显示。 几秒后自动消失。



GPT-4o给的回复



为了封装一个实用的工具类,实现一行代码即可调用 Snackbar 显示一个简短的信息,并支持错误类型、警告类型、消息类型、成功类型等不同的图标和信息,可以按照以下步骤进行实现:

  1. 创建一个 SnackbarUtil 工具类。
  2. 定义 SnackbarType 枚举类,表示不同类型的 Snackbar。
  3. 封装 showSnackbar 方法,以便一行代码即可调用 Snackbar。

完整代码示例

定义 SnackbarType 枚举类以及图标资源

首先定义 SnackbarType 枚举类和图标资源,以表示不同类型的 Snackbar 和对应的图标。


import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.ui.graphics.vector.ImageVector

enum class SnackbarType(val icon: ImageVector) {
    ERROR(Icons.Default.Error),
    WARNING(Icons.Default.Warning),
    INFO(Icons.Default.Info),
    SUCCESS(Icons.Default.CheckCircle)
}



创建 SnackbarUtil

接下来,创建 SnackbarUtil 工具类,封装一个用于显示 Snackbar 的方法。



import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

object SnackbarUtil {
    fun showSnackbar(
        scaffoldState: ScaffoldState,
        message: String,
        type: SnackbarType,
        durationMillis: Long = 3000 // Duration can be customized here
    ) {
        val scope = rememberCoroutineScope()
        scope.launch {
            scaffoldState.snackbarHostState.showSnackbar(
                message = message,
                actionLabel = null, // No action button
                duration = SnackbarDuration.Short
            )
            delay(durationMillis)
            scaffoldState.snackbarHostState.currentSnackbarData?.dismiss()
        }
    }
    
    @Composable
    fun CustomSnackbar(snackbarData: SnackbarData, type: SnackbarType) {
        Snackbar(
            modifier = Modifier.padding(8.dp)
        ) {
            Icon(
                imageVector = type.icon,
                contentDescription = null,
                modifier = Modifier.size(24.dp)
            )
            Spacer(modifier = Modifier.size(8.dp))
            Text(text = snackbarData.message)
        }
    }
}



使用 SnackbarUtil 在 UI层

我们在 UI 层调用 SnackbarUtil 来显示不同类型的 Snackbar。示例代码如下:



import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApp()
        }
    }
}

@Composable
fun MyApp() {
    val scaffoldState = rememberScaffoldState()

    Scaffold(
        scaffoldState = scaffoldState,
        topBar = {
            TopAppBar(title = { Text("Snackbar Example") })
        },
        content = {
            Column(
                Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = androidx.compose.ui.Alignment.CenterHorizontally
            ) {
                Button(onClick = {
                    SnackbarUtil.showSnackbar(
                        scaffoldState = scaffoldState,
                        message = "Error message",
                        type = SnackbarType.ERROR
                    )
                }) {
                    Text("Show Error")
                }
                Spacer(modifier = Modifier.height(16.dp))
                Button(onClick = {
                    SnackbarUtil.showSnackbar(
                        scaffoldState = scaffoldState,
                        message = "Warning message",
                        type = SnackbarType.WARNING
                    )
                }) {
                    Text("Show Warning")
                }
                Spacer(modifier = Modifier.height(16.dp))
                Button(onClick = {
                    SnackbarUtil.showSnackbar(
                        scaffoldState = scaffoldState,
                        message = "Info message",
                        type = SnackbarType.INFO
                    )
                }) {
                    Text("Show Info")
                }
                Spacer(modifier = Modifier.height(16.dp))
                Button(onClick = {
                    SnackbarUtil.showSnackbar(
                        scaffoldState = scaffoldState,
                        message = "Success message",
                        type = SnackbarType.SUCCESS
                    )
                }) {
                    Text("Show Success")
                }
            }
        },
        snackbarHost = {
            SnackbarHost(
                hostState = scaffoldState.snackbarHostState,
                snackbar = { snackbarData ->
                    SnackbarUtil.CustomSnackbar(snackbarData = snackbarData, type = SnackbarType.INFO) // Pass your type here
                }
            )
        }
    )
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MyApp()
}



上面有几个问题,

1、不需要CustomSnackbar,这个有点繁琐,没必要。

2、传参数 scafoldState, 应该不需要

3、 type参数也不需要, 直接封装成4个函数,给到用户。


我把上述要求给gpt说了, 最终它给了一个非常完美的代码




好的,我们可以进一步简化 SnackbarUtil,将 showSnackbarError、showSnackbarInfo、showSnackbarWarning 和 showSnackbarSuccess 四个函数分离出来,这样调用者就不需要传递 type 参数了。

更新后的 SnackbarUtil 工具类

SnackbarType 枚举类(保留用于内部)


工具类


import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.platform.LocalContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

object SnackbarUtil {
    @Composable
    private fun showSnackbar(
        message: String,
        type: SnackbarType,
        durationMillis: Long = 3000 // Duration can be customized here
    ) {
        val scaffoldState = rememberScaffoldState()
        val coroutineScope = rememberCoroutineScope()
        
        LaunchedEffect(key1 = message) {
            coroutineScope.launch {
                scaffoldState.snackbarHostState.showSnackbar(
                    message = message,
                    actionLabel = type.label,
                    duration = SnackbarDuration.Short
                )
                delay(durationMillis)
                scaffoldState.snackbarHostState.currentSnackbarData?.dismiss()
            }
        }

        // Connect this to the actual Scaffold in your UI
        Scaffold(snackbarHost = {
            SnackbarHost(hostState = scaffoldState.snackbarHostState)
        }) {}
    }

    @Composable
    fun showError(message: String, durationMillis: Long = 3000) {
        showSnackbar(message, SnackbarType.ERROR, durationMillis)
    }

    @Composable
    fun showWarning(message: String, durationMillis: Long = 3000) {
        showSnackbar(message, SnackbarType.WARNING, durationMillis)
    }

    @Composable
    fun showInfo(message: String, durationMillis: Long = 3000) {
        showSnackbar(message, SnackbarType.INFO, durationMillis)
    }

    @Composable
    fun showSuccess(message: String, durationMillis: Long = 3000) {
        showSnackbar(message, SnackbarType.SUCCESS, durationMillis)
    }
}





使用 SnackbarUtil 在 UI 层

在实际的 UI 组件中调用 SnackbarUtil 来显示不同类型的 Snackbar:



import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApp()
        }
    }
}

@Composable
fun MyApp() {
    Scaffold(
        topBar = {
            TopAppBar(title = { Text("Snackbar Example") })
        },
        content = {
            Column(
                Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Button(onClick = {
                    SnackbarUtil.showError("Error message")
                }) {
                    Text("Show Error")
                }
                Spacer(modifier = Modifier.height(16.dp))
                Button(onClick = {
                    SnackbarUtil.showWarning("Warning message")
                }) {
                    Text("Show Warning")
                }
                Spacer(modifier = Modifier.height(16.dp))
                Button(onClick = {
                    SnackbarUtil.showInfo("Info message")
                }) {
                    Text("Show Info")
                }
                Spacer(modifier = Modifier.height(16.dp))
                Button(onClick = {
                    SnackbarUtil.showSuccess("Success message")
                }) {
                    Text("Show Success")
                }
            }
        },
        snackbarHost = { SnackbarHost(hostState = rememberScaffoldState().snackbarHostState) }
    )
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MyApp()
}



解释:

  1. SnackbarType 枚举类:保留用于内部表示不同类型的 Snackbar,并且为每种类型指定了一个标签和图标。
  2. SnackbarUtil:
  • showSnackbar 私有组合函数:这是一个私有方法,现在所有具体类型的 Snackbar 都通过这个方法显示。
  • showError、showWarning、showInfo、showSuccess 组合函数:以上函数调用 showSnackbar,传递相应的 SnackbarType,这样调用者就不需要传递 type 参数了。
  1. MyApp 组件:
  • 使用 Scaffold 来搭建基本页面布局。
  • 每个按钮点击时会分别调用 SnackbarUtil.showError、SnackbarUtil.showWarning、SnackbarUtil.showInfo 和 SnackbarUtil.showSuccess 显示不同类型的 Snackbar。

通过这种方式,可以更加简洁地调用 SnackbarUtil.showError、SnackbarUtil.showWarning、SnackbarUtil.showInfo 和 SnackbarUtil.showSuccess 方法来显示不同类型的 Snackbar,使代码更加简洁和易于维护。





通义千问给的回复



在Kotlin与Jetpack Compose中,你可以创建一个实用的工具类来简化Snackbar的调用,使其能够通过一行代码展示不同类型的Snackbar消息,并带有自动消失功能。下面是一个示例实现:

SnackbarUtil.kt


package your.package.name.util

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.outlined.Warning
import androidx.compose.material.icons.rounded.CheckCircle
import androidx.compose.material.icons.rounded.ErrorOutline
import androidx.compose.material.icons.rounded.Info
import androidx.compose.material.icons.rounded.WarningAmber
import androidx.compose.material.snackbar.SnackbarDuration
import androidx.compose.material.snackbar.SnackbarResult
import androidx.compose.material.snackbar.SnackbarHost
import androidx.compose.material.snackbar.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import kotlinx.coroutines.delay

enum class SnackbarType {
    ERROR, WARNING, INFO, SUCCESS
}

object SnackbarUtil {
    @Composable
    fun showSnackbar(
        message: String,
        type: SnackbarType = SnackbarType.INFO,
        durationMs: Long = SnackbarDuration.Short.durationMillis,
    ) {
        val snackbarHostState = remember { SnackbarHostState() }
        val coroutineScope = remember { androidx.compose.runtime.currentComposer.coroutineScope }
        val context = LocalContext.current

        DisposableEffect(message) {
            LaunchedEffect(Unit) {
                delay(durationMs)
                snackbarHostState.showSnackbar(message = message)
            }

            onDispose {}
        }

        SnackbarHost(snackbarHostState) { data ->
            val icon = when (type) {
                SnackbarType.ERROR -> Icons.Filled.Error
                SnackbarType.WARNING -> Icons.Outlined.Warning
                SnackbarType.INFO -> Icons.Rounded.Info
                SnackbarType.SUCCESS -> Icons.Rounded.CheckCircle
            }

            Box(
                modifier = Modifier.fillMaxWidth(),
                contentAlignment = Alignment.CenterStart
            ) {
                // 在这里可以根据需要添加图标
                // 由于Compose Snackbar目前不直接支持图标,所以这里省略了图标的具体实现
                androidx.compose.material.Snackbar(
                    modifier = Modifier.align(Alignment.CenterStart),
                    action = {},
                    dismissAction = { snackbarHostState.currentSnackbarData?.dismiss() },
                    message = { androidx.compose.material.Text(message) }
                )
            }
        }
    }
}





使用示例

在你的Compose界面中,你可以这样调用SnackbarUtil.showSnackbar方法来显示不同类型的Snackbar:


import your.package.name.util.SnackbarType
import your.package.name.util.SnackbarUtil

// ...

@Composable
fun MyScreen() {
    Column(modifier = Modifier.fillMaxSize()) {
        // ... 其他组件
        Button(onClick = {
            SnackbarUtil.showSnackbar("操作成功", type = SnackbarType.SUCCESS)
        }) {
            Text("显示成功Snackbar")
        }
        Button(onClick = {
            SnackbarUtil.showSnackbar("警告信息", type = SnackbarType.WARNING)
        }) {
            Text("显示警告Snackbar")
        }
        // 类似地,添加更多按钮来测试其他类型的Snackbar
    }
}


在Kotlin与Jetpack Compose中实现Snackbar功能及相关概念,可以参考以下官方文档和资源:

  1. Jetpack Compose官方文档 - Snackbar: 虽然Compose的文档中并没有直接提供一个内置的带图标的Snackbar实现,但它详细介绍了如何使用SnackbarHost和SnackbarHostState来创建和管理Snackbar。
  1. Material Design Guidelines - Snackbars: Google的Material Design指南提供了关于Snackbars的设计原则和使用建议,帮助你理解何时以及如何使用它们。
  1. Compose状态与副作用: 了解如何在Compose中使用DisposableEffect和LaunchedEffect来管理状态和执行副作用,这对于实现定时自动消失的Snackbar非常关键。
  1. Coroutine延迟: 上述示例中使用了delay函数来实现延迟显示Snackbar,这是Kotlin协程的基本功能之一。
  1. 自定义Snackbar: 虽然上述示例中没有深入到如何添加图标,但如果你需要自定义Snackbar样式,包括添加图标,可以参考以下资源:
  1. 图标资源: Material Icons的官方页面,可以查找和下载各种图标资源。




Toast的详细使用


何时在Android应用中使用Toasts? (When to use Toasts in Android app?)

Toast messages are used to show the user something that isn’t critical but might help the user with what’s happening in the application currently. For example, giving a hint for a specific field in the form.

Toast消息用于向用户显示不重要的内容,但可能会帮助用户了解应用程序中当前发生的情况。 例如,为表单中的特定字段提供提示。

创建吐司的语法 (Syntax to Create a Toast)

We can use the Toast class to create a toast message.

我们可以使用Toast类创建一条Toast消息。

1. Toast.makeText(this, "Androidly Short Toasts", Toast.LENGTH_SHORT).show();
2. 
3. Toast.makeText(this, "Androidly Long Toasts", Toast.LENGTH_LONG).show();

Toast requires three arguments.

吐司需要三个参数。

  1. Context语境
  2. Message信息
  3. Duration持续时间

The show() function is used to display the Toast on the screen.

show()函数用于在屏幕上显示Toast。

We can customize the layout of the toast as well as its duration.

我们可以自定义吐司的布局及其持续时间。




相关文章
|
4月前
|
移动开发 前端开发 Android开发
【02】建立各项目录和页面标准化产品-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【02】建立各项目录和页面标准化产品-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
580 12
【02】建立各项目录和页面标准化产品-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
|
4月前
|
移动开发 JavaScript 应用服务中间件
【06】优化完善落地页样式内容-精度优化-vue加vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【06】优化完善落地页样式内容-精度优化-vue加vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
504 5
【06】优化完善落地页样式内容-精度优化-vue加vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
|
4月前
|
移动开发 Rust JavaScript
【01】首页建立-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【01】首页建立-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
896 4
【01】首页建立-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
|
5月前
|
开发工具 Android开发
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
680 11
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
|
4月前
|
移动开发 Android开发
【03】建立隐私关于等相关页面和内容-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【03】建立隐私关于等相关页面和内容-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
258 0
|
8月前
|
安全 Java Android开发
为什么大厂要求安卓开发者掌握Kotlin和Jetpack?深度解析现代Android开发生态优雅草卓伊凡
为什么大厂要求安卓开发者掌握Kotlin和Jetpack?深度解析现代Android开发生态优雅草卓伊凡
386 0
为什么大厂要求安卓开发者掌握Kotlin和Jetpack?深度解析现代Android开发生态优雅草卓伊凡
|
JSON 调度 数据库
Android面试之5个Kotlin深度面试题:协程、密封类和高阶函数
本文首发于公众号“AntDream”,欢迎微信搜索“AntDream”或扫描文章底部二维码关注,和我一起每天进步一点点。文章详细解析了Kotlin中的协程、扩展函数、高阶函数、密封类及`inline`和`reified`关键字在Android开发中的应用,帮助读者更好地理解和使用这些特性。
429 1
|
安全 Android开发 Kotlin
Android经典面试题之Kotlin延迟初始化的by lazy和lateinit有什么区别?
**Kotlin中的`by lazy`和`lateinit`都是延迟初始化技术。`by lazy`用于只读属性,线程安全,首次访问时初始化;`lateinit`用于可变属性,需手动初始化,非线程安全。`by lazy`支持线程安全模式选择,而`lateinit`适用于构造函数后初始化。选择依赖于属性特性和使用场景。**
709 5
Android经典面试题之Kotlin延迟初始化的by lazy和lateinit有什么区别?
|
Android开发 开发者 Kotlin
告别AsyncTask:一招教你用Kotlin协程重构Android应用,流畅度飙升的秘密武器
【9月更文挑战第13天】随着Android应用复杂度的增加,有效管理异步任务成为关键。Kotlin协程提供了一种优雅的并发操作处理方式,使异步编程更简单直观。本文通过具体示例介绍如何使用Kotlin协程优化Android应用性能,包括网络数据加载和UI更新。首先需在`build.gradle`中添加coroutines依赖。接着,通过定义挂起函数执行网络请求,并在`ViewModel`中使用`viewModelScope`启动协程,结合`Dispatchers.Main`更新UI,避免内存泄漏。使用协程不仅简化代码,还提升了程序健壮性。
506 1
|
调度 Android开发 开发者
【颠覆传统!】Kotlin协程魔法:解锁Android应用极速体验,带你领略多线程优化的无限魅力!
【8月更文挑战第12天】多线程对现代Android应用至关重要,能显著提升性能与体验。本文探讨Kotlin中的高效多线程实践。首先,理解主线程(UI线程)的角色,避免阻塞它。Kotlin协程作为轻量级线程,简化异步编程。示例展示了如何使用`kotlinx.coroutines`库创建协程,执行后台任务而不影响UI。此外,通过协程与Retrofit结合,实现了网络数据的异步加载,并安全地更新UI。协程不仅提高代码可读性,还能确保程序高效运行,不阻塞主线程,是构建高性能Android应用的关键。
289 4