You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android Navigation组件的nav_graph.xml中使用Parcelable类型Safe Args

出现java.lang.IllegalArgumentException: Could not find animation.name in Bundle报错的原因是:导航组件的label属性默认只能直接读取Bundle根层级的参数,无法自动解析Parcelable类型参数内部的字段,你在xml中写@{animation.name}时,系统会直接去Bundle中查找key为animation.name的参数,而不会先取出animation对象再读取它的name属性,因此匹配不到对应参数。

你不需要单独传递name字符串,依旧只传递整个animation对象即可,按以下步骤操作就能实现需求:

  1. 修改nav_graph.xml中SecondFragment的label配置,删掉你之前写的@{animation.name}绑定表达式,设置一个默认占位值即可,示例:
<fragment
    android:id="@+id/secondFragment"
    android:name="com.yourpackage.SecondFragment"
    android:label="默认标题" >
    <argument
        android:name="animation"
        app:argType="com.yourpackage.Animation" />
</fragment>
  1. 在SecondFragment中拿到传递过来的animation对象后,动态设置当前目的地的label即可:
  • Kotlin代码示例:
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs

class SecondFragment : Fragment() {
    private val args: SecondFragmentArgs by navArgs()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val animation = args.animation
        // 动态设置当前页面的label
        findNavController().currentDestination?.label = animation.name
    }
}
  • Java代码示例:
public class SecondFragment extends Fragment {
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        SecondFragmentArgs args = SecondFragmentArgs.fromBundle(getArguments());
        Animation animation = args.getAnimation();
        NavController navController = Navigation.findNavController(view);
        NavDestination currentDestination = navController.getCurrentDestination();
        if (currentDestination != null) {
            currentDestination.setLabel(animation.getName());
        }
    }
}

内容的提问来源于stack exchange,提问作者Mohammad Charousaei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 15:24:05