Jetpack Compose:未找到 ViewTreeLifecycleOwner

时间:2021-05-18 12:33:30

标签: android android-jetpack-compose

在我的片段中使用 Compose 时出现此错误,在 XML 的情况下工作正常

ViewTreeLifecycleOwner not found from androidx.fragment.app.FragmentContainerView

我使用的是单一活动方法没有使用 Jetpack Navigation 组件

活动

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"

1 个答案:

答案 0 :(得分:2)

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

添加:

implementation 'androidx.appcompat:appcompat:1.3.0'