You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose自定义Toast实现报错求助及相关方案咨询

Jetpack Compose自定义Toast实现报错求助及相关方案咨询

我想实现一个自定义样式的Toast,请问该怎么操作呢?

我现在写的代码已经被标记为废弃了,而且运行时会崩溃,崩溃日志如下:

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)这个方法来修改Toast的背景和图标呢?

编辑补充:后来发现用Scaffold搭配Snackbar是一个可行的解决方案

备注:内容来源于stack exchange,提问作者user21300258

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 10:34:52