带有可为空的可打包参数的编译中的Android数据绑定错误

问题描述

我想将我创建的Parcelable类Payment通过一个带有安全参数的片段从一个片段传递到另一个片段,但是它可以为空。

我创建了类型为com.example.Payment的参数,并将其设置为可为空。编译应用程序时,我在构建文件夹下的Expression in a class literal has a nullable type 'Payment?',use !! to make the type non-nullable中看到错误FragmentDirection

此行中发生错误

@Suppress("CAST_NEVER_SUCCEEDS")
class FragmentDirections private constructor(
 {    
   private data class GoToNew(
       val Payment: Payment?
     ) : NavDirections {

      override fun getArguments(): Bundle {
         val result = Bundle()
         if (Parcelable::class.java.isAssignableFrom(Payment::class.java)) { // Error happend here,when trying to get the class of Payment
           result.putParcelable("Payment",this.Payment as Parcelable?)
         } else if (Serializable::class.java.isAssignableFrom(Payment::class.java)) { // There is also the same error here
           result.putSerializable("Payment",this.Payment as Serializable?)
         } else {
           throw UnsupportedOperationException(Payment::class.java.name +
               " must implement Parcelable or Serializable or must be an Enum.") // and here
         }
         return result
       }
//...
}

我不知道我做错了什么,并且由于文件在构建文件夹下而无法编辑。

编辑: 有导航的xml代码

<navigation 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:id="@+id/main_navigation"
    app:startDestination="@id/listFragment">
    <fragment
        android:id="@+id/newPaymentFragment"
        android:name="com.example.wallet.application.newPayment.NewPaymentFragment"
        android:label="fragment_new_payment"
        tools:layout="@layout/fragment_new_payment" >
        <argument android:name="Payment"
            app:argType="com.example.Payment"
            app:nullable="true"/>
        <action
            android:id="@+id/backToList"
            app:destination="@id/listFragment" />
        <action
            android:id="@+id/goToDetail"
            app:destination="@id/detailFragment" />
    </fragment>
    <!-- ... -->

</navigation>

解决方法

在模块级gradle文件中,将apply plugin: "androidx.navigation.safeargs.kotlin"更改为apply plugin: "androidx.navigation.safeargs"。我已经尝试过了,现在可以正常工作了。

,

更改您的<argument android:name="Payment"><argument android:name="payment"