Question

I'm using a ViewPager together with a FragmentStatePagerAdapter, and I would like to launch an animation in a fragment when this fragment is visible and only when it is visible. The problem is that the animation starts when the fragment is the one after the one who is currently seen by the user. I moved the animation code from the "onActivityCreated" fragment function to the "onStart" fragment function, and even to the "onResume" fragment function, but the same thing happens.

Basically I need to wait for the fragment to be the page seen by the user to launch some code. How can I do that?

Thanks in advance.

Was it helpful?

Solution

I made it.

    CustomOnPageChangeListener page_listener = new CustomOnPageChangeListener();
    view_pager.setOnPageChangeListener(page_listener);

    ...

    private static class CustomOnPageChangeListener extends SimpleOnPageChangeListener
    {
        @Override
        public void onPageSelected(int position)
        {
            if (position == fragment_position)
            {
                 MyFragment fragment = (MyFragment) fragment_pager_adapter.instantiateItem(view_pager, fragment_position);
                 fragment.startAnimation();
            }

            super.onPageSelected(position);
        }
    }

and, of course, you must write a startAnimation() function that launches the animation into the MyFragment code.

OTHER TIPS

Have you tried using the following:

@Override
public void onWindowFocusChanged (boolean hasFocus) {
   super.onWindowFocusChanged(hasFocus);
   if (hasFocus)
      myTextView.startAnimation(anim);
}

You can override setUserVisibleHint inside your fragment

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (mAnimation == null)
        return;

    if (isVisibleToUser) {
        mAnimation.resumeAnimation();
    } else {
        mAnimation.pauseAnimation();
    }
}

Use this. Worked for FragmentStatePagerAdapter perfectly.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
  super.setUserVisibleHint(isVisibleToUser);
  if (isVisibleToUser) { 
      // TODO
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top