Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 633
JHowzer Avatar asked Nov 29 '18 18:11

JHowzer


People also ask

How do you pass an enum as an argument?

enums are technically descendants of Enum class. So, if you want to use only Enum's standard methods in your method (such as values()), pass the parameter like this: static void printEnumValue(Enum generalInformation) See, that the only thing you have to change is the capital letter E.

What is SafeArgs?

SafeArgs is a gradle plugin that allows you to Pass data to destination UI components. It generates simple object and builder classes for type-safe navigation and access to any associated arguments. Safe Args is strongly recommended for navigating and passing data because it ensures type-safety.


1 Answers

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

like image 69
ianhanniballake Avatar answered Sep 18 '22 07:09

ianhanniballake