Jetpack Compose:未找到 ViewTreeLifecycleOwner

Jetpack Compose : ViewTreeLifecycleOwner not found

我在片段中使用 Compose 时遇到此错误,在 XML

的情况下工作正常

ViewTreeLifecycleOwner not found from androidx.fragment.app.FragmentContainerView

我正在使用单一 activity 方法 没有 使用 Jetpack Navigation 组件

Activity:

override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  setContentView(R.layout.activity_nav)
  supportFragmentManager.commit {
    setReorderingAllowed(true)
    add<InboxFragment>(R.id.nav_fragmentContainerView_appNav)
  }
}
<androidx.fragment.app.FragmentContainerView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/nav_fragmentContainerView_appNav"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>

片段:

override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
): View {
  return ComposeView(requireContext()).apply {
    setContent {
      Text(text = "HELLO FRIEND!")
    }
  }
}

依赖关系:

def fragment_version = "1.3.3"
implementation("androidx.fragment:fragment-ktx:$fragment_version")

def compose_version = "1.0.0-beta06"
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.ui:ui-tooling:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.activity:activity-compose:1.3.0-alpha07"
classpath "com.android.tools.build:gradle:7.0.0-alpha15"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.30"

由于您使用的是 AppCompatActivity,因此只有 appcompat 1.3 版本会填充 ViewTreeLifecycleOwner

添加:

implementation 'androidx.appcompat:appcompat:1.3.0'