Search code examples
javaandroidandroid-fragmentsandroid-architecture-componentsandroid-architecture-navigation

How to apply transition to fragments using the new Navigation Graph?


I have created an animation using XML for fade in and out and attached it to the fragment using the drop down in navigation drop for enter and exit but the fragments are not being animated.

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/navigation_graph"
app:startDestination="@id/mainFragment">

<fragment
    android:id="@+id/mainFragment"
    android:name="com.cheapapps.randomquotesmachine.MainFragment"
    android:label="fragment_main"
    tools:layout="@layout/fragment_main">
    <action
        android:id="@+id/action_mainFragment_to_quoteDetailFragment"
        app:destination="@id/quoteDetailFragment"
        app:enterAnim="@anim/fade_in"
        app:exitAnim="@anim/fade_out" />
</fragment>
<fragment
    android:id="@+id/quoteDetailFragment"
    android:name="com.cheapapps.randomquotesmachine.QuoteDetailFragment"
    android:label="fragment_quote_detail"
    tools:layout="@layout/fragment_quote_detail">
    <argument
        android:name="position"
        android:defaultValue="0"
        app:argType="integer" />
</fragment>
</navigation>

Solution

  • I'm not sure how your fade_in and fade_out files look like so I'll provide you an example below:

    <?xml version="1.0" encoding="utf-8"?>
    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:fromAlpha="0.0" android:toAlpha="1.0"
        android:duration="500" />
    

    And:

    <?xml version="1.0" encoding="utf-8"?>
    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:fromAlpha="1.0" android:toAlpha="0.0"
        android:fillAfter="true"
        android:duration="500" />
    

    To apply this fade transition to your fragments, you should set enterAnim and exitAnim as you already did but together with popEnterAnim and popExitAnim as in the following example:

    <action android:id="@+id/action_mainFragment_to_quoteDetailFragment"
        app:destination="@id/quoteDetailFragment"
        app:popEnterAnim="@anim/fade_in"
        app:popExitAnim="@anim/fade_out"
        app:enterAnim="@anim/fade_in"
        app:exitAnim="@anim/fade_out"/>