0

I am trying to do some animation inside ViewPager2 with Fragments.

But the problem is when I load the animation from XML, it is working for the first time. After swiping left/right in ViewPager and going back to the same page that animation is not working.

Below is the XML anim

<?xml version="1.0" encoding="UTF-8"?>
<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="infinite"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="4000" />

Below is the code which I used to load the animation inside Fragment

Animation rotate = AnimationUtils.loadAnimation(getContext(), R.anim.rotate);
view.startAnimation(rotate);

I have also done some animation without loading from XML, it was working perfectly fine. That problem only occurs when I load the animation from XML.

AskNilesh
  • 67,701
  • 16
  • 123
  • 163

2 Answers2

0

Try using repetition on your animation object.

rotate.setRepeatCount(Animation.INFINITE);

OR

(Animation.RESTRT)

OR setInterpolator() on animation

Write your animation code inside onPageSelected()

View pager OnPageChangeListener

Prashant.J
  • 739
  • 7
  • 12
0

You are calling startAnimation() inside onCreateView() at that point view is just getting created but not visible on screen that is why the animation is not getting started call startAnimation() inside onStart();

@Override
public void onStart() {
    super.onStart();
    Animation rotate = AnimationUtils.loadAnimation(getContext(), R.anim.rotate);
    view.startAnimation(rotate);
}
Rahul Samaddar
  • 244
  • 2
  • 8
  • I am using FragmentStateAdapter for ViewPager Adapter, which is not calling onStart() when I need focus in that fragment after swipe left/right. So, adding ```startAnimation()``` inside ```onResume()``` fixed my issue. – vijay raghavan Apr 13 '20 at 19:10