如何知道片段何时进入转换结束?

时间:2015-11-24 13:31:12

标签: android android-fragments android-animation

我有一个片段,显示输入动画,我按

设置过渡
this.setEnterTransition(transition);

之后我想展示另一个动画。但我需要知道转换动画何时结束才能开始第二个动画。

对于活动,有一个类似onEnterAnimationComplete()的回调,但在Fragment的转换结束时不会调用它。

有没有办法知道何时输入片段的转换结束?

2 个答案:

答案 0 :(得分:3)

transition.addListener(new Transition.TransitionListener() {
                    @Override
                    public void onTransitionStart(Transition transition) {}

                    @Override
                    public void onTransitionEnd(Transition transition) {}

                    @Override
                    public void onTransitionCancel(Transition transition) {}

                    @Override
                    public void onTransitionPause(Transition transition) {}

                    @Override
                    public void onTransitionResume(Transition transition) {}
                });

                this.setEnterTransition(transition);

答案 1 :(得分:1)

如果您有以下设置:

FragmentA使用SharedElementEnterTransition调用FragmentB,如

private final TransitionSet transition = new TransitionSet()
        .addTransition(new ChangeBounds());
//...
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, fragment, fragment.getClass().getSimpleName());

transaction.addSharedElement(view, view.getTransitionName());
fragment.setSharedElementEnterTransition(transition);
fragment.setSharedElementReturnTransition(transition);
transaction.commit();

在第二个片段中侦听SharedElementTransition的结束。然后你必须在FragmentB的onAttach中获得SharedElementEnterTransition,如:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    TransitionSet transitionSet = (TransitionSet) getSharedElementEnterTransition();
    if (transitionSet != null) {
        transitionSet.addListener(new Transition.TransitionListener() {
            @Override
            public void onTransitionEnd(@NonNull Transition transition) {
                // remove listener as otherwise there are side-effects
                transition.removeListener(this);
                // do something here
            }

            @Override
            public void onTransitionStart(@NonNull Transition transition) {}
            @Override
            public void onTransitionCancel(@NonNull Transition transition) {}
            @Override
            public void onTransitionPause(@NonNull Transition transition) {}
            @Override
            public void onTransitionResume(@NonNull Transition transition) {}
        });
    }
}

正如this answer的评论中指出的那样,在onAttach()中没有设置监听器时会出现错误。