androidandroid-viewpagerfragmentonstart

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.


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.