[英]What is the correct way to pass an Enum as an argument to a Fragment using Navigation Component safeargs
The documentation discusses how to send simple integers and strings.该文档讨论了如何发送简单的整数和字符串。 For example:例如:
<argument
android:name="myIntArg"
android:defaultValue="255"
app:argType="integer" />
In the origin Fragment:在原始片段中:
val action = OriginFragmentDirections.myAction(myInt)
findNavController().navigate(action)
In the destination Fragment:在目标片段中:
val receivedInt = DestinationFragmentArgs.fromBundle(arguments).myIntArg
But say instead of myIntArg
, I wanted to send an enum ( myEnumArg
).但是说而不是myIntArg
,我想发送一个枚举( myEnumArg
)。 How would I do that?我该怎么做? What app:argType
would I use in my argument?我会在我的论点中使用什么app:argType
?
Edit: As per the Navigation 1.0.0-alpha08 release notes :编辑:根据Navigation 1.0.0-alpha08 发行说明:
Safe Args supports Serializable objects, including Enum values. Safe Args 支持 Serializable 对象,包括 Enum 值。 Enum types can set a default value by using the enum literal without the class name (eg
app:defaultValue="READ"
) b/111316353枚举类型可以通过使用没有类名的枚举文字来设置默认值(例如app:defaultValue="READ"
) b/111316353
So this is now possible - you would use the name of your Enum class (ie, com.example.EnumClass
) or a relative name ( .EnumClass
) which will automatically prepend your app's package name to the class name.所以这现在是可能的 - 您可以使用 Enum 类的名称(即com.example.EnumClass
)或相对名称( .EnumClass
),它会自动将您的应用程序的包名称添加到类名称之前。
Previous answer:上一个答案:
This is not possible with the current version of Navigation (1.0.0-alpha07), but the existing feature request is marked as fixed and the ability to use enums as arguments will be available in alpha08这在当前版本的 Navigation (1.0.0-alpha07) 中是不可能的,但是现有的功能请求被标记为固定的,并且在 alpha08 中将提供使用枚举作为参数的能力
As @ianhanniballake mentioned in his updated answer, you need to use the latest version of Navigation.正如@ianhanniballake 在他更新的答案中提到的,您需要使用最新版本的 Navigation。
Assume we have an Enum like below and your app package name is com.example.app
.假设我们有一个像下面这样的Enum并且您的应用程序包名称是com.example.app
。
package com.example.app.path.to.type.file
public enum class Type {
First,
Second,
Third
}
Now we just need to declare the Arg like this:现在我们只需要像这样声明 Arg:
<fragment
...>
<argument
android:name="type"
android:defaultValue="Second"
app:argType=".path.to.type.file.Type" />
...
</fragment>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.