我想展示定制吐司。如何实现这一目标?
这是我的代码,但它已被弃用,并且会因日志而崩溃:
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 是一个解决方案
试试这个
@Composable
fun ShowToast(){
val context= LocalContext.current
Toast.makeText(context, "Invalid credentials. Please try again.", Toast.LENGTH_SHORT).show()
}
Snackbar是最推荐的。 但如果您想使用“Toast”,您可以定义自己的可组合项。
@Composable
fun Toast(message:String){
makeText(LocalContext.current,message, Toast.LENGTH_SHORT).show()
}
确保导入 导入 android.widget.Toast 导入 android.widget.Toast.makeText