Android : Difference between action id and fragment id in navigation component
Asked Answered
R

1

11

I have a question that is bugging me for a long time,

In navigation component, when using .navigate(int resId) what makes a difference in passing an action id vs fragment id?

example:

<fragment android:id="@+id/loginFragment"
          android:name="com.example.myapp.ui.main.LoginFragment"
          android:label="@string/login"
          tools:layout="@layout/fragment_login" >

    <action
        android:id="@+id/action_login_to_emailLoginFragment"
        app:destination="@id/emailLoginFragment"
        app:popEnterAnim="@anim/slide_in_right"
        app:popExitAnim="@anim/slide_out_right"
        app:popUpTo="@+id/emailLoginFragment"
        app:popUpToInclusive="true"/>

</fragment>

<fragment android:id="@+id/emailLoginFragment"
          android:name="com.example.myapp.ui.main.EmailLoginFragment"
          android:label="EmailLoginFragment"
          tools:layout="@layout/fragment_login_email" />

In the above scenario, what will be the difference if

1) use .navigate(R.id.action_login_to_emailLoginFragment);

2) use .navigate(R.id.emailLoginFragment);

And i have one more query, I know that .navigate(int resId) will replace the fragment, in that case how to retain state of views in previous fragment?

Rosannrosanna answered 7/9, 2019 at 2:57 Comment(1)
You should only ask one question at a time, but to answer your second question: any Fragment on the back stack automatically has its state saved and restored (same as if your device was rotated and went through a configuration change, etc).Gigue
G
11

All of the other attributes on an action - i.e., the popEnterAnim, popExitAnim, popUpTo, and popUpToInclusive are part of a NavOptions object that is automatically applied when you use that action id.

Therefore when you use navigate(R.id.emailLoginFragment), none of the other fields are applied: you won't pop anything off the back stack nor will any animations be applied. To duplicate what the action provides, you'd need to use the navigate(int, Bundle, NavOptions) method, manually constructing the correct NavOptions.

Gigue answered 7/9, 2019 at 4:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.