【问题标题】:Preventing fragment custom animations from playing on screen rotation?防止片段自定义动画在屏幕旋转上播放?
【发布时间】:2012-07-11 20:58:16
【问题描述】:

我在 FragmentTransaction 中为我的秒表片段使用自定义动画。代码如下:

private void addStopWatch() {
    if(_stopwatchFragment == null) {
        _stopwatchFragment = new StopwatchFragment();

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.setCustomAnimations(R.anim.anim_slide_down, R.anim.anim_slide_up)
                           .add(R.id.ContentContainer, _stopwatchFragment, STOPWATCH_TAG)
                           .commit();

        _stopwatchVisible = true;
    }
}

每当屏幕旋转时,就会再次播放 R.anim.anim_slide_down 动画(这里我不是添加新片段,而是重新附加已经存在的片段)。有没有办法避免这种行为,只让片段与活动视图一起出现?

【问题讨论】:

    标签: android android-fragments


    【解决方案1】:

    这可以通过在活动中使用静态字段轻松解决。将其声明为活动类的静态成员:

    private static boolean hasAnimated = false;
    

    然后在你的方法中你可以这样做:

    private void addStopWatch() {
        if(_stopwatchFragment == null) {
            _stopwatchFragment = new StopwatchFragment();
    
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    
            if(!hasAnimated) {
                fragmentTransaction.setCustomAnimations(R.anim.anim_slide_down, R.anim.anim_slide_up)
                                   .add(R.id.ContentContainer, _stopwatchFragment, STOPWATCH_TAG)
                                   .commit();
                hasAnimated = true
            } else {
                fragmentTransaction.add(R.id.ContentContainer, _stopwatchFragment, STOPWATCH_TAG)
                                   .commit();
            }
    
            _stopwatchVisible = true;
        }
    }
    

    虽然我不确定这是否需要对活动破坏进行适当的清理。可以肯定的是,在 onDestroy() 中将 hasAnimated 设置为 false。

    【讨论】:

    • 简单而优雅的解决方案,我希望我能想到它:) 谢谢。
    猜你喜欢
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多