Jetpack Compose - 无虚拟方法 setContent

问题描述 投票:0回答:1

我想将 Jetpack Compose 添加到我的 Android 应用程序中。 库已添加(根据教程以及 Google 的示例应用程序)。我使用Kotlin 1.9.20,编译JVM版本是Java 17。 该 Activity 是一个 AppCompatActivity(),因此它应该与 compose 兼容。

build.gradle 文件添加了以下行:

compileOptions {
    sourceCompatibility = 17
    targetCompatibility = 17
}

with(kotlinOptions) {
    jvmTarget = "17"
    languageVersion = 1.9
}

buildFeatures {
    compose = true
}
composeOptions {
    kotlinCompilerExtensionVersion = "1.5.4"
}

以及库的最小版本:

implementation(platform("androidx.compose:compose-bom:2023.10.01"))
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.material:material")
implementation("androidx.compose.ui:ui-tooling-preview")

所以一切看起来都很好。 但是,当我添加 composeView 时,我得到一个异常,如下所示:

NoSuchMethodError:没有虚拟方法 setContent(Lkotlin/jvm/functions/Function0;)V 在类中 Landroidx/compose/ui/platform/ComposeView;

对于使用 XML 布局的简化代码,在布局中添加 ComposeView,如下所示:

composeView = view.findViewById(R.id.compose_view)
composeView.setContent {
  ...
}

在第一行中,我已经可以看到 XML 布局的 composeView。它是一个 ComposeView。只是下一行失败了。

我还尝试将我的整个片段作为 Compose 的容器。

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return ComposeView(requireContext()).apply {
           setViewCompositionStrategy(
               ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {
                // In Compose world
                MaterialTheme {
                    MyLayout()
                }
            }
        }
    }

我仍然遇到同样的错误:

java.lang.NoSuchMethodError: No virtual method setContent(Lkotlin/jvm/functions/Function0;)V in class Landroidx/compose/ui/platform/ComposeView; or its super classes
     (declaration of 'androidx.compose.ui.platform.ComposeView' appears in /data/app/~~XE01rsSoScPaH1MnxHjNsA==/.../base.apk)
     at myFragment.onCreateView(MyFragment.kt:30)
     at androidx.fragment.app.Fragment.performCreateView(Fragment.java:3114)
android gradle android-gradle-plugin android-jetpack-compose
1个回答
0
投票

我相信你只需要添加这个依赖项:

implementation("androidx.activity:activity-compose")

© www.soinside.com 2019 - 2024. All rights reserved.