androidandroid-jetpack-composeandroid-toast

Toast with compose ui is crashing with exception "viewtreelifecycleowner not found from androidx.compose.ui.platform.composeview"


val context = LocalContext.current
        Button(onClick = {
            val toast = android.widget.Toast(context)
            val composeView = ComposeView(context)
            composeView.setContent { ToastUi() }
            toast.view = composeView
            toast.show()
        }
        ) { Text(text = "Show toast") }

 @Composable
 fun ToastUi() {
        Row {
            Icon(painter = painterResource(id = R.drawable.ic_success_colored),"")
            Spacer(modifier = Modifier.width(12.dp))
            Text("sample")
        }
    }

on button click the application crashes with exception "viewtreelifecycleowner not found from androidx.compose.ui.platform.composeview"


Solution

  • val toast: Toast = Toast(this).apply {
            duration = Toast.LENGTH_LONG + Toast.LENGTH_SHORT
            view = ComposeView(this@ToastActivity).apply {
                setOwners()
                setContent { TestProjectTheme { ToastLayout() } }
            }
        }
    
    private fun ComposeView.setOwners() {
    if (ViewTreeLifecycleOwner.get(this) == null)
        ViewTreeLifecycleOwner.set(this, context as LifecycleOwner)
    if (ViewTreeViewModelStoreOwner.get(this) == null)
        ViewTreeViewModelStoreOwner.set(this, context as ViewModelStoreOwner)
    if (ViewTreeSavedStateRegistryOwner.get(this) == null)
        ViewTreeSavedStateRegistryOwner.set(this, context as SavedStateRegistryOwner)}