2

In my activity or fragment I used method:

 public void replaceFragment(Fragment fragment, boolean addToBackStack) {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction(); transaction.setCustomAnimations(R.anim.slide_in_right, 0);
        if (addToBackStack) {
            transaction.addToBackStack(null);
        }
        transaction.replace(R.id.mFrameContainer, fragment);
        transaction.commitAllowingStateLoss();
    }

when replace fragment. I run but in some screen have load data from sever, it's lag when show fragment so I want when animation finish I will call method load data. So how I can check finish animation replace fragment. I search and see in stack over but I still can't do it. If you have answer for my question, please share to me! Thank you very much!

  • Give [this](http://stackoverflow.com/questions/11120372/performing-action-after-fragment-transaction-animation-is-finished) a shot. You'll have to change it to an `Animation`, but it allows you to use an `AnimationListener`. – Dillon Burton May 22 '17 at 06:40
  • @DillonBurton How I can call onCreateAnimation instaed of setCustomAnimations – Hoa Tran Van May 22 '17 at 07:03
  • You will still call everything like you have it, except you will override `onCreateAnimation` inside of your fragment, and run your code inside of `onAnimationEnd`. – Dillon Burton May 22 '17 at 07:08
  • @DillonBurton it mean I must remove transaction.setCustomAnimations(R.anim.slide_in_right, 0); and add R.anim.slide_in_right in onCreateAnimation ? – Hoa Tran Van May 22 '17 at 07:11
  • I'll add an answer to show you what I mean. – Dillon Burton May 22 '17 at 07:17

1 Answers1

1

Instead of importing import android.app.Fragment;, use import android.support.v4.app.Fragment;. Change getFragmentManager in your replaceFragment method with getSupportFragmentManager. Then, in your fragment class, add the following:

@Override
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {

    Animation anim = AnimationUtils.loadAnimation(getActivity(), nextAnim);

    anim.setAnimationListener(new Animation.AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            // TODO: This is where you will put your code for when the animation is finished
        }
    });

    return anim;
}

Put the code you want to execute after in onAnimationEnd.

Dillon Burton
  • 131
  • 10