Jetpack Compose:未找到 ViewTreeLifecycleOwner

Arr*_*row 3 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)
  }
}
Run Code Online (Sandbox Code Playgroud)
<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"/>
Run Code Online (Sandbox Code Playgroud)

片段

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

依赖项

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"
Run Code Online (Sandbox Code Playgroud)
classpath "com.android.tools.build:gradle:7.0.0-alpha15"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.30"
Run Code Online (Sandbox Code Playgroud)

Age*_*t_L 7

这只是一个简单的名称更改,从具有静态方法的类更改为扩展方法:

ViewTreeLifecycleOwner.get(view)改为View.findViewTreeLifecycleOwner()
ViewTreeLifecycleOwner.set()View.setViewTreeLifecycleOwner(lifecycleOwner: LifecycleOwner?)


Gab*_*tti 5

由于您使用的是AppCompatActivity,因此只有 appcompat1.3版本会填充ViewTreeLifecycleOwner.

添加:

implementation 'androidx.appcompat:appcompat:1.3.0'
Run Code Online (Sandbox Code Playgroud)

  • appcompat 1.4.2 上存在同样的问题。有什么建议么? (3认同)