导航组件重复 NavArgs 的问题

2024-05-19

我有一个片段:

class SomeFragment {
    private val args by navArgs<SomeFragmentArgs>()
}

该片段用于两个导航图中:

第一个_nav.xml

....
<fragment
    android:id="@+id/initialFragment"
    android:name="com.example.InitialFragment"
    android:label="Initial Fragment">
    <action
        android:id="@+id/action_to_some_fragment"
        app:destination="@id/someFragment" />
</fragment>
<fragment
    android:id="@+id/someFragment"
    android:name="com.example.SomeFragment"
    android:label="Some Label">
    <argument
        android:name="someType"
        app:argType="com.example.someType"/>
</fragment>
....

第二个_nav.xml

....
<fragment
    android:id="@+id/initialFragment2"
    android:name="com.example.InitialFragment2"
    android:label="Initial Fragment">
    <action
        android:id="@+id/action_to_some_fragment"
        app:destination="@id/someFragment" />
</fragment>
<fragment
    android:id="@+id/someFragment"
    android:name="com.example.SomeFragment"
    android:label="Some Label">
    <argument
        android:name="someType"
        app:argType="com.example.someType"/>
</fragment>
....

但是当我构建 R8 版本的项目时,会抛出:

R8:程序类型已存在:com.example.SomeFragmentArgs$Companion

谁可以帮我这个事?


我也面临这个问题。我们采用多模块开发,方向类在不同的模块中生成。这样到处都有几个 FragmentDirections 并导致 R8 程序类型已经存在,因为它们都有伴生对象。

有两种解决方案/解决方法。

  1. 将此片段隔离成独立的navigation.xml

在你的情况下,你可以写一个 some_fragment_nav.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"
app:startDestination="@id/someFragment"
android:id="@+id/some_fragment_nav">

<fragment
    android:id="@+id/someFragment"
    android:name="com.example.SomeFragment"
    android:label="lable">

    <action
        android:id="@+id/what_ever_action_you_want"
        app:destination="@id/share_this_id_to_ids" />


    <argument
        android:name="someType"
        app:argType="com.example.someType"/>

</fragment>

</navigation>

and use

<include app:graph="@navigation/some_fragment_nav"/>

在两个导航图中。那可行。如果您使用多模块开发。您需要通过将您的 id 写入 ids.xml 来共享操作 id。

  1. 将 SomeFragment 复制并粘贴到不同的命名中,例如 SomeFragment1.kt SomeFragment2.kt。并且也不会存在任何 R8 程序类型。此外,您可以将 SomeFragment 作为开放类,并将 SomeFragment1 扩展为具有空实现的 SomeFragment。

我个人的前景.. 2 比 1 更好,因为它们对我来说都是解决方法。直到jetbrains改变了生成的FragmentDirection类的规则。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

导航组件重复 NavArgs 的问题 的相关文章

随机推荐