Jetpack Compose - Problem with BottomSheetDialogFragment and ViewTreeLifecycleOwner

Viewed 1731

After updating the Jetpack Compose library to beta01, I'm not able to show DialogFragment or BottomSheetDialogFragment. Looks like ViewTreeLifecycleOwner cannot be found in my activity anymore. Also, I tried a couple of possible solutions but there are not any success.

The view in fragment is inflated with:

 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(
                R.layout.fragment_full_screen_layout, container, false
        ).apply {
            findViewById<ComposeView>(R.id.compose_view).setContent {...}

and dialog fragment is showing with:

DialogFragmentExample.newInstance().show(supportFragmentManager, null)

Does anyone have a similar problem? Please, any suggestion would be welcome.

Stacktracke:

java.lang.IllegalStateException: ViewTreeLifecycleOwner not found from DecorView@409dd5d[MainActivity]
        at androidx.compose.ui.platform.WindowRecomposer_androidKt.createLifecycleAwareViewTreeRecomposer(WindowRecomposer.android.kt:214)
        at androidx.compose.ui.platform.WindowRecomposer_androidKt.access$createLifecycleAwareViewTreeRecomposer(WindowRecomposer.android.kt:1)
        at androidx.compose.ui.platform.WindowRecomposerFactory$Companion$LifecycleAware$1.createRecomposer(WindowRecomposer.android.kt:98)
        at androidx.compose.ui.platform.WindowRecomposerPolicy.createAndInstallWindowRecomposer$ui_release(WindowRecomposer.android.kt:151)
        at androidx.compose.ui.platform.WindowRecomposer_androidKt.getWindowRecomposer(WindowRecomposer.android.kt:199)
        at androidx.compose.ui.platform.AbstractComposeView.ensureCompositionCreated(ComposeView.android.kt:177)
        at androidx.compose.ui.platform.AbstractComposeView.onAttachedToWindow(ComposeView.android.kt:222)
2 Answers

I get the same exception without even using a DialogFragment.

My workaround is to set the ViewTreeLifecycleOwner from the Activity:

class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)

      ViewTreeLifecycleOwner.set(window.decorView, this)
      // setContent(...); add fragment using Compose view
   }
}

I'm currently using the following libraries:

  • androidx.activity:activity-ktx:1.3.0-alpha04
  • androidx.fragment:fragment-ktx:1.3.1
  • androidx.compose.*:*:1.0.0-beta02

As per the Fragment 1.3.1 release notes:

Dialogs within a DialogFragment can now get access to ViewTree owners through their DecorView, ensuring that DialogFragment can be used with ComposeView. (Ib9290, b/180691023)

So you should make sure you upgrade to Fragment 1.3.1:

implementation "androidx.fragment:fragment-ktx:1.3.1"
Related