I use navigation library and safeargs for passing data. I define argument to fragment like that.
I forgot to apply plugin in app.gradle
file, just add this line
apply plugin: "androidx.navigation.safeargs.kotlin"
or this line if you are using java
apply plugin: "androidx.navigation.safeargs"
Took a bit to figure out but you need both action and arguments in your nav xml file to generate both.
<fragment
android:id="@+id/nav_someId"
android:name=".CategoriesFragment"
android:label="@string/someName"
tools:layout="@layout/fragment_categories">
<argument
android:name="@string/category"
android:defaultValue="0"
app:argType="string" />
<action
android:id="@+id/startCategoriesFragment"
app:destination="@+id/categoriesFragment">
<argument
android:name="@string/category"
android:defaultValue="0"
app:argType="string" />
</action>
</fragment>
Following two steps works for me:
Android studio 4.0 Kotlin 1.3.72
Also make sure to use an up to date version. Had the problem, that I had an 1.X version.
// Navigation
implementation "androidx.navigation:navigation-fragment-ktx:2.2.1"
implementation "androidx.navigation:navigation-ui-ktx:2.2.1"
And the args correctely in the nav.xml:
<fragment
android:id="@+id/categoryFragment"
android:name="com...CategoryFragment"
android:label="CategoryFragment"
tools:layout="@layout/fragment_category">
<action
android:id="@+id/action_categoryFragment_to_ProductFragment" // /!\
app:destination="@id/productFragment"
<argument
android:name="products"
android:defaultValue=""
app:argType="string" />
</action>
</fragment>
Code:
override fun onItemClicked(category: Category) {
val action = CategoryFragmentDirections.actionCategoryToProductFragment(products = "myString") // /!\
view?.findNavController()?.navigate(action)
}
the problem may be with your apply plugin
thing
please check if you are using java then add:
apply plugin: "androidx.navigation.safeargs"
and for kotlin use this:
apply plugin: "androidx.navigation.safeargs.kotlin"
I faced a similar issue working with android studio 4.2 preview.
The issue was that the IDE somehow was not picking the source folders where the generated direction classes where being placed by the plugin. So adding the following to my app build.gradle file resolved the issue for me.
sourceSets {
main {
java {
srcDirs += 'build/generated/source/navigation-args'
}
}
}
Hope this helps!