Android Navigation Component参数为何无法使用字符串资源?
问题场景
在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属性本身支持接收资源引用类型,所以可以正常使用。
解决方案
- 代码中补全默认值:不在XML中设置默认值,在Fragment初始化或导航跳转时,手动从资源中获取字符串并赋值参数。比如在Fragment的
onCreate方法中检查参数,若为空则填充默认值:
val fragmentKey = arguments?.getString("FragmentKey") ?: getString(R.string.title_notifications)
- 修改参数类型为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
相关产品推荐
相关产品推荐

