如何使用jetpack compose显示自定义Toast?

问题描述 投票:0回答:2

我想展示定制吐司。如何实现这一目标?

这是我的代码,但它已被弃用,并且会因日志而崩溃:

java.lang.IllegalStateException: ViewTreeLifecycleOwner not found from androidx.compose.ui.platform.ComposeView{3ed3fe7 V.E...... ......I. 0,0-0,0}
        Toast
            .makeText(context, "TESTTESTTEST", Toast.LENGTH_SHORT)
            .apply {
                view = ComposeView(context).apply {
                    setContent {
                        CustomToastWithIcon(
                            message = stringResource(id = R.string.cart),
                            ImageVector.vectorResource(id = R.drawable.ic_info)
                        )
                    }
                }
            }
            .show()

我尝试这样定义它,但仍然崩溃。

        val composeView = ComposeView(context).apply {
            setViewTreeLifecycleOwner(this.findViewTreeLifecycleOwner())
            setContent {
                CustomToastWithIcon(
                    message = stringResource(id = R.string.cart),
                    ImageVector.vectorResource(id = R.drawable.ic_info)
                )
            }

另请阅读: Jetpack Compose 中的自定义 Toast

或者是否可以从功能中更改背景和图标

        Toast
            .makeText(context, message, Toast.LENGTH_SHORT)

编辑: 带脚手架的 Snackbar 是一个解决方案

android kotlin android-jetpack-compose android-toast
2个回答
0
投票

试试这个

@Composable
fun ShowToast(){
    val context= LocalContext.current
    Toast.makeText(context, "Invalid credentials. Please try again.", Toast.LENGTH_SHORT).show()
}

-3
投票

Snackbar是最推荐的。 但如果您想使用“Toast”,您可以定义自己的可组合项。

@Composable
fun Toast(message:String){
    makeText(LocalContext.current,message, Toast.LENGTH_SHORT).show()
}

确保导入 导入 android.widget.Toast 导入 android.widget.Toast.makeText

© www.soinside.com 2019 - 2024. All rights reserved.