0

I would like to show custom toast. How to achieve this?

This is my code, but this is deprecated and it crashes with logs:

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()

I tried defining it like this, but still crash.

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

Also read: Custom Toast in Jetpack Compose

Or is it possible to change background and icon from function

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

Edit: Snackbar with scaffold was a solution

  • Does this answer your question? [Custom Toast in Jetpack Compose](https://stackoverflow.com/questions/69813731/custom-toast-in-jetpack-compose) – Abhimanyu Jun 20 '23 at 15:04

1 Answers1

0

Snackbar is mostly recommended. But if you want to use "Toast", you can define your own composable.

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

Make sure to import import android.widget.Toast import android.widget.Toast.makeText