【问题标题】:Jetpack Compose inside Fragment ViewTreeLifecycleOwner not found from ConstraintLayout从 ConstraintLayout 中找不到 Fragment ViewTreeLifecycleOwner 内的 Jetpack Compose
【发布时间】:2021-10-18 00:04:05
【问题描述】:

在我的片段中使用 Compose 时出现IllegalStateException 错误。

java.lang.IllegalStateException: ViewTreeLifecycleOwner not found from androidx.constraintlayout.widget.ConstraintLayout

活动是 AppCompatActivity:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

我正在使用Navigation Component 在片段之间导航。这是活动 XML:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/appContent"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/main_navigation_graph" />

</androidx.constraintlayout.widget.ConstraintLayout>

和片段:

class WelcomeFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return ComposeView(requireContext()).apply {
            setViewCompositionStrategy(
                DisposeOnLifecycleDestroyed(viewLifecycleOwner)
            )

            setContent {
                MaterialTheme {
                    Text(text = "Welcome to App")
                }
            }
        }
    }
}

依赖和版本:

FragmentVersion = '1.3.3'
CONSTRAINT_LAYOUT_VERSION = '2.1.0'
KOTLIN_VERSION = '1.5.21'
ACTIVITY_KTX_VERSION = '1.3.1'

COMPOSE_VERSION = '1.0.0'
COMPOSE_ACTIVITY = '1.3.1'
COMPOSE_VIEWMODEL = '1.0.0-alpha07'
COMPOSE_CONSTRAINT_VERSION = '1.0.0-beta02'
APP_COMPAT_VERSION = '1.3.1'

【问题讨论】:

    标签: android android-fragments android-constraintlayout androidx android-jetpack-compose


    【解决方案1】:

    问题已经通过从AppCompatActivity切换到FragmentAcivity解决了!!!

    【讨论】:

      【解决方案2】:

      希望这对其他人有所帮助,但我实际上发现问题是我的 app/build.gradle 中有旧版本的 AppCompatActivity 库,您应该将其更新到至少 1.3.0 或更高版本 类似于这个答案所暗示的: https://stackoverflow.com/a/67586890/14158634

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-01
        • 2023-03-28
        • 1970-01-01
        • 2021-06-29
        • 2021-04-21
        • 1970-01-01
        • 2021-12-28
        相关资源
        最近更新 更多