Android Navigation中使用Safe Args传递Long类型值失败如何解决?
Absolutely, you can pass Long (or long) type arguments using Safe Args—let’s get to the bottom of why your setup is generating String types instead, and fix it step by step.
First, Confirm Your Safe Args Setup is Up-to-Date
Older versions of the Safe Args plugin had limited support for primitive types, so make sure you’re using a recent stable version.
- Project-level build configuration (in
build.gradleorsettings.gradlefor newer Android Studio projects):buildscript { dependencies { classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.7.5" // Use the latest stable version } } - App-module build configuration:
At the top of your app’sbuild.gradlefile, apply the plugin:plugins { id 'com.android.application' id 'androidx.navigation.safeargs' // Add 'androidx.navigation.safeargs.kotlin' if you're using Kotlin }
Correct Navigation Graph Parameter Configuration
Your existing XML is close, but double-check the app:type value and add optional nullability if needed (this helps the plugin generate the correct type):
<fragment android:id="@+id/myFragment" android:name="com.x.app.y.MyFragment" android:label="fragment_mine" tools:layout="@layout/fragment_mine"> <argument android:name="row_id" app:type="long" app:nullable="false" /> <!-- Set to true if the parameter can be null --> </fragment>
The app:type="long" (lowercase) tells Safe Args to generate a long (Java) or Long (Kotlin) type for the parameter.
Fixing Incorrect Generated Code (Cache Issue)
If you’re still seeing String types after fixing the configuration, this is almost always a build cache problem:
- Go to Build > Clean Project in Android Studio
- Then run Build > Rebuild Project
This forces the Safe Args plugin to regenerate the navigation classes from scratch, using your updated parameter configuration.
Using the Generated Long Parameter
Once the code is regenerated correctly, you can use it like this:
For Java:
// Navigate to MyFragment with a Long parameter MyFragmentDirections.ActionToMyFragment action = MyFragmentDirections.actionToMyFragment(123L); Navigation.findNavController(view).navigate(action); // Retrieve the parameter in MyFragment long rowId = MyFragmentArgs.fromBundle(getArguments()).getRowId();
For Kotlin:
// Navigate to MyFragment with a Long parameter val action = MyFragmentDirections.actionToMyFragment(123L) findNavController().navigate(action) // Retrieve the parameter in MyFragment val args = MyFragmentArgs.fromBundle(requireArguments()) val rowId = args.rowId
Supported Safe Args Types (for Reference)
To avoid confusion later, here’s a quick list of supported types and their generated counterparts:
string→Stringinteger→int(Java) /Int(Kotlin)long→long(Java) /Long(Kotlin)float→float(Java) /Float(Kotlin)boolean→boolean(Java) /Boolean(Kotlin)reference→int(for resource IDs)custom→ CustomParcelable/Serializabletypes
内容的提问来源于stack exchange,提问作者Topper Harley

