【问题标题】:Model class doesn't find in KMM proyect which use Navigation Component在使用导航组件的 KMM 项目中找不到模型类
【发布时间】:2022-01-06 10:58:13
【问题描述】:

我正在开发一个使用 Kotlin Multiplatform 插件的应用程序,我尝试使用 Navigation 组件在我的应用程序的不同片段之间导航。

我的问题是由于 KMM proyect 与常规 Android Proyect 相比结构复杂。

当我尝试运行我的 proyect 时,使用它的 FragmentArgs 类找不到生成的不同导航组件类。

也就是说,在KMM中,用户界面是分开在不同的文件夹中的,业务逻辑是另一个类,数据库也是。

在这个捕获中可以看到 KMM proyec 的规则结构:

所以在我的 DetailFragmentArgs 中生成的错误是这样的:

error: cannot find symbol
    private final UnplashPhoto photo = null;
                  ^
  symbol:   class UnplashPhoto

我的 nav.graph.xml 的代码如下:

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/nav_graph"
    app:startDestination="@id/HomeFragment">

    <fragment
        android:id="@+id/HomeFragment"
        android:name="com.jshvarts.kmp.android.home.HomeFragment"
        android:label="HomeFragment" >
        <action
            android:id="@+id/action_navigate_from_home_to_detail"
            app:destination="@id/DetailFragment">
            <argument
                android:name="photo"
                app:argType="shared.src.commonMain.kotlin.com.jshvarts.kmp.model.UnplashPhoto"/>
        </action>
    </fragment>
    <fragment
        android:id="@+id/DetailFragment"
        android:name="com.jshvarts.kmp.android.detail.DetailFragment"
        android:label="DetailFragment" >
        <argument
            android:name="photo"
            app:argType="shared.src.commonMain.kotlin.com.jshvarts.kmp.model.UnplashPhoto"/>
    </fragment>
</navigation>

我尝试了一些路径,但不起作用:从存储库、从内容根目录和源根目录。

如果您在 KMM 插件方面更有经验并在某个时候处理过这个问题,欢迎您提供帮助!

提前致谢!

【问题讨论】:

    标签: android kotlin kmm


    【解决方案1】:

    在您的 build.gradle 中添加以下内容

    plugins {
       id ("kotlin-android-extensions")
    }
    
    kotlin {
        android{
            androidExtensions {
                isExperimental = true
            }
        }
    

    .....

    在你的 commonMain 中添加以下内容

    expect interface Parcelable
    @OptIn(ExperimentalMultiplatform::class)
    @OptionalExpectation
    @Target(AnnotationTarget.CLASS)
    @Retention(AnnotationRetention.BINARY)
    expect annotation class Parcelize()
    

    在你的 androidMain 中

    actual typealias Parcelable = android.os.Parcelable
    actual typealias Parcelize = kotlinx.android.parcel.Parcelize
    

    然后用Parcelize注释你的模型并实现Parcelable

    【讨论】:

      猜你喜欢
      • 2022-08-18
      • 2021-10-08
      • 2021-03-03
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多