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.
The Fragment API provides two ways to use motion effects and transformations to visually connect fragments during navigation. One of these is the Animation Framework, which uses both Animation and Animator. The other is the Transition Framework, which includes shared element transitions.
First, you need to create animations for your enter and exit effects, which are run when navigating to a new fragment. You can define animations as tween animation resources . These resources allow you to define how fragments should rotate, stretch, fade, and move during the animation.
The current fragment slides off the screen to the right while the previous fragment fades in. Once you've defined your animations, use them by calling FragmentTransaction.setCustomAnimations () , passing in your animation resources by their resource ID, as shown in the following example:
A FragmentManager manages Fragments in Android, specifically, it handles transactions between fragments. A transaction is a way to add, replace, or remove fragments. getPageTitle (int pos): (optional) Similar to getItem () this methods returns the title of the page at index pos.
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.
Have you tried using the following:
@Override
public void onWindowFocusChanged (boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus)
myTextView.startAnimation(anim);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With