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

Android Navigation Component参数为何无法使用字符串资源?

Android Navigation组件中argument默认值无法引用字符串资源的问题

问题场景

在navigation.xml中配置Fragment导航参数时遇到如下问题:

  • 字符串资源@string/title_notifications在Fragment的label属性中可正常使用
  • 但将其设为<argument>标签的android:defaultValue时触发编译报错,直接写字符串字面量"Notifications"则编译正常

配置代码

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mobile_navigation"
    app:startDestination="@+id/navigation_home">

    <fragment
        android:id="@+id/navigation_notifications"
        android:name="com.elyeproj.bottombarfragmentsswitching.ContainerFragment"
        android:label="@string/title_notifications"
        tools:layout="@layout/fragment_container" >
        <argument
            android:name="FragmentKey"
            app:argType="string"
            android:defaultValue="@string/title_notifications" />
        <argument
            android:name="FragmentColor"
            app:argType="string"
            android:defaultValue="#00FFFF" />
    </fragment>
</navigation>

报错信息

Caused by: org.xmlpull.v1.XmlPullParserException: unsupported value 'Notifications' for string. You must use a "reference" type to reference other resources.

原因与解决方案

原因

Navigation组件对<argument>标签的android:defaultValue属性有严格的类型匹配要求:
当声明app:argType="string"时,框架期望默认值是字符串字面量,而资源引用@string/xxx属于reference类型,和指定的string类型不兼容,因此触发解析错误。而Fragment的label属性本身支持接收资源引用类型,所以可以正常使用。

解决方案

  1. 代码中补全默认值:不在XML中设置默认值,在Fragment初始化或导航跳转时,手动从资源中获取字符串并赋值参数。比如在Fragment的onCreate方法中检查参数,若为空则填充默认值:
val fragmentKey = arguments?.getString("FragmentKey") 
    ?: getString(R.string.title_notifications)
  1. 修改参数类型为reference:如果要在XML中使用资源引用作为默认值,需要将app:argType改为reference,此时参数的接收类型为Int(资源ID),之后在代码中通过资源ID获取字符串:
<argument
    android:name="FragmentKey"
    app:argType="reference"
    android:defaultValue="@string/title_notifications" />

代码中获取:

val fragmentKeyResId = arguments?.getInt("FragmentKey") ?: R.string.title_notifications
val fragmentKey = getString(fragmentKeyResId)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 23:30:50