thomaus
thomaus

Reputation: 6258

Start animation when fragment is visible on ViewPager

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.

Upvotes: 5

Views: 5546

Answers (4)

Vlad
Vlad

Reputation: 1018

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();
    }
}

Upvotes: 1

kaftanati
kaftanati

Reputation: 480

Use this. Worked for FragmentStatePagerAdapter perfectly.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
  super.setUserVisibleHint(isVisibleToUser);
  if (isVisibleToUser) { 
      // TODO
  }
}

Upvotes: 0

thomaus
thomaus

Reputation: 6258

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.

Upvotes: 8

jnthnjns
jnthnjns

Reputation: 8925

Have you tried using the following:

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

Upvotes: 1

Related Questions