使用导航组件 safeargs 将枚举作为参数传递给片段的正确方法是什么
What is the correct way to pass an Enum as an argument to a Fragment using Navigation Component safeargs
documentation 讨论了如何发送简单的整数和字符串。例如:
<argument
android:name="myIntArg"
android:defaultValue="255"
app:argType="integer" />
在原始片段中:
val action = OriginFragmentDirections.myAction(myInt)
findNavController().navigate(action)
在目标片段中:
val receivedInt = DestinationFragmentArgs.fromBundle(arguments).myIntArg
但是我想发送一个枚举 (myEnumArg
) 而不是 myIntArg
。我该怎么做? app:argType
我会在我的论证中使用什么?
编辑: 根据 Navigation 1.0.0-alpha08 release notes:
Safe Args supports Serializable objects, including Enum values. Enum types can set a default value by using the enum literal without the class name (e.g. app:defaultValue="READ"
) b/111316353
所以这现在是可能的 - 您可以使用枚举的名称 class(即 com.example.EnumClass
)或相对名称 (.EnumClass
),这将自动在您的应用程序的前面加上包名称到 class 名称。
上一个回答:
当前版本的 Navigation (1.0.0-alpha07) 无法做到这一点,但 existing feature request 已标记为已修复,使用枚举作为参数的功能将在 alpha08[=16] 中可用=]
正如@ianhanniballake 在他更新的回答中提到的,您需要使用最新版本的导航。
假设我们有一个如下所示的 Enum 并且您的应用程序包名称是 com.example.app
.
package com.example.app.path.to.type.file
public enum class Type {
First,
Second,
Third
}
现在我们只需要像这样声明 Arg:
<fragment
...>
<argument
android:name="type"
android:defaultValue="Second"
app:argType=".path.to.type.file.Type" />
...
</fragment>
documentation 讨论了如何发送简单的整数和字符串。例如:
<argument
android:name="myIntArg"
android:defaultValue="255"
app:argType="integer" />
在原始片段中:
val action = OriginFragmentDirections.myAction(myInt)
findNavController().navigate(action)
在目标片段中:
val receivedInt = DestinationFragmentArgs.fromBundle(arguments).myIntArg
但是我想发送一个枚举 (myEnumArg
) 而不是 myIntArg
。我该怎么做? app:argType
我会在我的论证中使用什么?
编辑: 根据 Navigation 1.0.0-alpha08 release notes:
Safe Args supports Serializable objects, including Enum values. Enum types can set a default value by using the enum literal without the class name (e.g.
app:defaultValue="READ"
) b/111316353
所以这现在是可能的 - 您可以使用枚举的名称 class(即 com.example.EnumClass
)或相对名称 (.EnumClass
),这将自动在您的应用程序的前面加上包名称到 class 名称。
上一个回答:
当前版本的 Navigation (1.0.0-alpha07) 无法做到这一点,但 existing feature request 已标记为已修复,使用枚举作为参数的功能将在 alpha08[=16] 中可用=]
正如@ianhanniballake 在他更新的回答中提到的,您需要使用最新版本的导航。
假设我们有一个如下所示的 Enum 并且您的应用程序包名称是 com.example.app
.
package com.example.app.path.to.type.file
public enum class Type {
First,
Second,
Third
}
现在我们只需要像这样声明 Arg:
<fragment
...>
<argument
android:name="type"
android:defaultValue="Second"
app:argType=".path.to.type.file.Type" />
...
</fragment>