26

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). How would I do that? What app:argType would I use in my argument?

JHowzer
  • 3,684
  • 4
  • 30
  • 36

3 Answers3

25

Edit: As per the 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

So this is now possible - you would use the name of your Enum class (i.e., com.example.EnumClass) or a relative name (.EnumClass) which will automatically prepend your app's package name to the class name.

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

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
23

As @ianhanniballake mentioned in his updated answer, you need to use the latest version of Navigation.

Assume we have an Enum like below and your app package name is 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:

<fragment
    ...>
    <argument
        android:name="type"
        android:defaultValue="Second"
        app:argType=".path.to.type.file.Type" />
...
</fragment>
Hassan TBT
  • 805
  • 7
  • 5
1

For those wondering how this would be done with Compose, according to NavType.EnumType you just use NavType.EnumType:

composable(
     YOUR_ROUTE,
     arguments = listOf(navArgument(ARGUMENT_NAME) {
                    type = NavType.EnumType(YOUR_ENUM::class.java)
                 }
     )
)
AlbertSawZ
  • 51
  • 6