首页 > 解决方案 > 如何从 SafeArgs 中的资源中获取默认字符串值?

问题描述

我正在学习 Android NavigationUI,并尝试使用 Safe Args 中的字符串默认值设置工具栏标题。但是有一些问题。

“字符串资源”文件:

    <string name="title_add_item">Add new items</string>

导航图文件。将标签设置为Title: {title}参数。

<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/mainFragment">

<fragment
    android:id="@+id/addNewItemFragment"
    android:name="com.myapplication.AddNewItemFragment"
    android:label="Title: {title}"
    tools:layout="@layout/fragment_add_new_item" >
    <argument
        android:name="title"
        app:argType="string"
        android:defaultValue="@string/title_add_item" />
</fragment>
<fragment
    android:id="@+id/mainFragment"
    android:name="com.myapplication.MainFragment"
    android:label="fragment_main"
    tools:layout="@layout/fragment_main" >
    <action
        android:id="@+id/action_to_add_items_fragment"
        app:destination="@id/addNewItemFragment" />
</fragment>

如果{app:argType="string"}我收到错误:

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

如果 {app:argType="reference"}应用程序有效,但我在标题中有一个数字(我认为这是一个资源 ID):

在此处输入图像描述

当然,我可以通过从参数中获取它来分配代码中工具栏标题的值。但是是否可以更改此代码以正确填写标题?

标签: androidstringandroidxandroid-navigationandroid-safe-args

解决方案


仅在引用类型中支持对资源的引用。在任何其他类型中使用资源引用都会导致异常。

随意给现有问题加注星标:https ://issuetracker.google.com/issues/167959935 。目前,您可以使用硬编码字符串值app:argType="string"或尝试以编程方式设置,直到它得到解决。

在此处输入图像描述


推荐阅读