【问题标题】:Exception Inflating nav_graph when passing Parcelable object between Navigation Fragments在导航片段之间传递 Parcelable 对象时出现异常膨胀 nav_graph
【发布时间】:2020-04-05 01:38:37
【问题描述】:

我试图在导航片段之间传递一个对象。我能够构建该项目,但是当它启动时,我在 nav_graph 上收到一条错误消息:“异常膨胀 nav_graph 第 20 行”。第 20 行是 nav_graph 上的参数行。我刚刚将@Parcelize 关键字添加到我试图传递并设置nav_graph 的类的顶部。我需要做其他事情吗?

团队班:

@Parcelize
public class Team {
@SerializedName("idTeam")
@Expose
private String idTeam;
@SerializedName("idSoccerXML")
@Expose
private String idSoccerXML;
@SerializedName("idAPIfootball")
@Expose
private String idAPIfootball;
@SerializedName("intLoved")
@Expose
private String intLoved;
@SerializedName("strTeam")
@Expose
private String strTeam;
@SerializedName("strTeamShort")
@Expose
private String strTeamShort;

Nav_Graph:

<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/nav_graph"
app:startDestination="@id/homeFragment">
<fragment
    android:id="@+id/homeFragment"
    android:name="com.jaykallen.searchapi.ui.HomeFragment"
    android:label="HomeFragment">
    <action
        android:id="@+id/action_homeFragment_to_resultsFragment"
        app:destination="@id/resultsFragment" />
</fragment>
<fragment
    android:id="@+id/resultsFragment"
    android:name="com.jaykallen.searchapi.ui.ResultsFragment"
    android:label="ResultsFragment">
    <argument
        android:name="choice"
        app:argType="com.jaykallen.searchapi.model.Team"
        app:nullable="true" />
</fragment>
</navigation>

HomeFragment 方法:

private fun choiceClicked(chosen: Team) {
    println("User clicked: ${chosen.strTeam}")
    homeViewModel.choice = chosen
    val action = HomeFragmentDirections.actionHomeFragmentToResultsFragment(chosen)
    Navigation.findNavController(view!!).navigate(action)
}

ResultsFragment 方法:

private fun getSafeArgs() {
    arguments?.let {
        val args = ResultsFragmentArgs.fromBundle(it)
        teamChosen = args.choice
        if (teamChosen != null) {
            println("Safe Argument Received=${teamChosen?.strTeam}")
            updateUi(teamChosen)
        }
    }
}

【问题讨论】:

  • 请编辑您的问题并提供异常的完整堆栈跟踪。

标签: android android-jetpack-navigation android-safe-args


【解决方案1】:

事实证明,您需要做的就是在您的 Java 对象上实现 Parcelable 接口。通常,如果您使用 Kotlin,@Parcelize 注释将不允许您在没有 Parcelable 接口的情况下进行编译。似乎这种编译时保护不适用于 Java 代码。

通过使用 Java 对象,您还将失去 @Parcelize 注释附带的所有自动代码生成功能。

换句话说,如果您想利用 @Parcelize 注释,我建议您将 Java 文件转换为 Kotlin。

【讨论】:

  • 做到了,现在我的安全参数可以发送一个对象了!我必须将我的 pojo 类转换为 Kotlin,然后将 Parcelable 添加为接口。即@Parcelize 类团队:Parcelable {
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-07
  • 1970-01-01
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多