Start animation when fragment is visible on ViewPager

I use ViewPager along with the FragmentStatePagerAdapter, and I would like to start the animation in the 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 that was after the one who is currently being viewed by the user. I moved the animation code from the onActivityCreated snippet function to the onStart snippet function and even to the onResume snippet function, but the same thing happens.

Basically, I need to wait until the fragment becomes the page that the user sees to run the code. How can i do this?

Thanks in advance.

+4
source share
3 answers

I have done 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 have to write the startAnimation () function, which starts the animation in MyFragment code.

+8
source

You tried to use the following:

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

Use this. Works great for the FragmentStatePagerAdapter.

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

All Articles