FragmentTransaction 在 setCustomAnimation 前后的回调问题

9

我正在使用自定义动画来替换片段,我想在动画开始时禁用一些按钮,并在动画结束时启用它们。我该怎么做?

1个回答

28

我建议创建一个基类,让你的所有Fragments都继承它,并在其中定义一些方法,可以被覆盖以处理动画事件。然后,重写onCreateAnimation()(假设你正在使用支持库),以在动画回调上发送事件。例如:

protected void onAnimationStarted () {}

protected void onAnimationEnded () {}

protected void onAnimationRepeated () {}

@Override
public Animation onCreateAnimation (int transit, boolean enter, int nextAnim) {
    //Check if the superclass already created the animation
    Animation anim = super.onCreateAnimation(transit, enter, nextAnim);

    //If not, and an animation is defined, load it now
    if (anim == null && nextAnim != 0) {
        anim = AnimationUtils.loadAnimation(getActivity(), nextAnim);
    }

    //If there is an animation for this fragment, add a listener.
    if (anim != null) {
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart (Animation animation) {
                onAnimationStarted();
            }

            @Override
            public void onAnimationEnd (Animation animation) {
                onAnimationEnded();
            }

            @Override
            public void onAnimationRepeat (Animation animation) {
                onAnimationRepeated();
            }
        });
    }

    return anim;
}

然后,对于你的Fragment子类,只需覆盖onAnimationStarted()以禁用按钮,以及onAnimationEnded()以启用按钮。


3
这在材料过渡(如滑动或爆炸)中无法使用,因为 anim 始终为 null。 - Servus7
为什么 transit 和 nextAnim 总是为零?! - Mohammad Afrashteh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接