Home > front end >  Fragment transaction with animation
Fragment transaction with animation

Time:09-16

I'm new to android, and I'm trying to replace fragment with fragment transaction. But i couldn't succssided to make a linear animation.

Can some one help me?

Thanks in advance

CodePudding user response:

You can create animations in XML like this -

<!-- res/anim/fade_out.xml -->
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_shortAnimTime"
    android:interpolator="@android:anim/decelerate_interpolator"
    android:fromAlpha="1"
    android:toAlpha="0" />
<!-- res/anim/slide_in.xml -->
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_shortAnimTime"
    android:interpolator="@android:anim/decelerate_interpolator"
    android:fromXDelta="100%"
    android:toXDelta="0%" />

Add above code in 2 different XML files and place those files unde res/anim directory.

Then while replacing your fragment, just apply these animations like this -

val fragment = FragmentB()
supportFragmentManager.commit {
    setCustomAnimations(
        enter = R.anim.slide_in,
        exit = R.anim.fade_out
    )
    replace(R.id.fragment_container, fragment)
    addToBackStack(null)
}

More info - https://developer.android.com/guide/fragments/animate#set-animations

CodePudding user response:

Create, for example, 2 files fragment_from_left.xml and fragment_from_right.xml in anim folder with this code:

fragment_from_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set>
    <translate xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromXDelta="-100%"
        android:toXDelta="0"
        android:interpolator="@android:anim/decelerate_interpolator"
        android:duration="500"/>
</set>

fragment_from_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set>
    <translate xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromXDelta="100%"
        android:toXDelta="0"
        android:interpolator="@android:anim/decelerate_interpolator"
        android:duration="500"/>
</set>

this will make your fragment appear from left. You can use another interpolator (this one slows down animation speed from start to end) Then in your java code do this:

getSupportFragmentManager().beginTransaction()
                .setCustomAnimations(R.anim.fragment_from_right, R.anim.fragment_to_left, R.anim.fragment_from_left, R.anim.fragment_to_right)
                .addToBackStack(null).replace(R.id.main_container, fragment).commit();

Now your fragments will appear with animation.

  • Related