2

我想将连续动画(比如 ScaleAnimation)应用于显示资源图像的 ImageView。动画由按钮触发。例如,我想在每次单击按钮时逐步放大图像。

我在动画上设置了 fillAfter="true"。但是,所有的动画都是从 ImageView 的原始状态开始的。看起来好像 ImageView 重置了它的状态并且动画总是一样的,而不是从上一个动画的最终状态开始。

我究竟做错了什么?

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button button = (Button)findViewById(R.id.Button01);
    button.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            animate();

        }});
}

private void animate() {
    ImageView imageView = (ImageView) findViewById(R.id.ImageView01);

    ScaleAnimation scale = new ScaleAnimation((float)1.0, (float)1.5, (float)1.0, (float)1.5);
    scale.setFillAfter(true);
    scale.setDuration(500);
    imageView.startAnimation(scale); 
}
4

2 回答 2

3

看起来好像 ImageView 重置了它的状态并且动画总是一样的,而不是从上一个动画的最终状态开始。

恰恰!我确定有一个用途 for fillAfter="true",但我还没有弄清楚它的意义。

您需要做的是AnimationListener在每个Animation相关性上设置一个,并在侦听器中做一些事情onAnimationEnd()以实际保持动画的最终状态。我没有玩过,ScaleAnimation所以我不太确定“坚持最终状态”的方式是什么。例如,如果这是一个AlphaAnimation,从1.0to 0.0,您将制作小部件INVISIBLEGONEin onAnimationEnd()

于 2010-04-01T22:34:37.490 回答
1

我遇到了同样的问题并创建了以下代码以轻松使用不同的动画。它目前只支持平移和 alpha 级别,因为我没有使用缩放,但可以轻松扩展以支持更多功能。

我在开始动画之前重置了滚动和可见性,但这只是因为我需要开/关动画。

并且“doEnd”布尔值是为了避免递归堆栈溢出(scrollTo 调用 onAnimationEnd 出于某种晦涩的原因......)

private void setViewPos(View view, Animation anim, long time){
    // Get the transformation
    Transformation trans = new Transformation();
    anim.getTransformation(time, trans);

    // Get the matrix values
    float[] values = new float[9];
    Matrix m = trans.getMatrix();
    m.getValues(values);

    // Get the position and apply the scroll
    final float x = values[Matrix.MTRANS_X];
    final float y = values[Matrix.MTRANS_Y];
    view.scrollTo(-(int)x, -(int)y);

    // Show/hide depending on final alpha level
    if (trans.getAlpha() > 0.5){
        view.setVisibility(VISIBLE);
    } else {
        view.setVisibility(INVISIBLE);       
    }
}

private void applyAnimation(final View view, final Animation anim){
    view.scrollTo(0, 0);
    view.setVisibility(VISIBLE);

    anim.setAnimationListener(new AnimationListener(){
        private boolean doEnd = true;

        @Override
        public void onAnimationEnd(Animation animation) {
            if (doEnd){
                doEnd = false;
                setViewPos(view, animation, anim.getStartTime() + anim.getDuration());
            }
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationStart(Animation animation) {
        }

    });

    view.startAnimation(anim);
}
于 2010-09-10T13:44:08.163 回答