在ACTION_UP上删除了Android onTouch动画

时间:2011-06-03 01:46:32

标签: java android animation

这应该相当简单,但结果却比我想象的要复杂得多。如何将ScaleAnimation应用于视图并使其在指压的整个持续时间内保持不变?换句话说,当他的手指向下缩小视图直到手指被移除,然后将其恢复到原始大小? 这就是我的尝试:

public void onTouch(View v, MotionEvent event)
{
    switch(event.getAction())
    {
    case MotionEvent.ACTION_DOWN
    {
        v.setAnimation(shrinkAnim);
    }
    case MotionEvent.ACTION_UP
    {
        v.setAnimation(growAnim);
    }
    }
}

如果我应用setFillEnabled(true)setFillAfter(true),那么收缩将无限期地保留。如果我不使用它会收缩一秒然后恢复正常。提前谢谢

2 个答案:

答案 0 :(得分:4)

您忘记了break;

public void onTouch(View v, MotionEvent event) {
    switch(event.getAction()) {
        case MotionEvent.ACTION_DOWN:
             v.setAnimation(shrinkAnim);
             break;

        case MotionEvent.ACTION_UP:
             v.setAnimation(growAnim);
             break;

        default:
             // never without default!
    }
}

答案 1 :(得分:2)

有点不清楚你有什么,没有尝试过什么组合,所以这里有一个有效的例子:

Animation shrink, grow;

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

    //I chose onCreate(), but make the animations however suits you.
    //The animations need only be created once.

    //From 100% to 70% about center
    shrink = new ScaleAnimation(1.0f, 0.7f, 1.0f, 0.7f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f, ScaleAnimation.RELATIVE_TO_SELF,0.5f);
    shrink.setDuration(200);
    shrink.setFillAfter(true);

    //From 70% to 100% about center
    grow = new ScaleAnimation(0.7f, 1.0f, 0.7f, 1.0f, ScaleAnimation.RELATIVE_TO_SELF,0.5f,ScaleAnimation.RELATIVE_TO_SELF,0.5f);
    grow.setDuration(200);
    grow.setFillAfter(true);
}

@Override
public void onTouch(View v, MotionEvent event) {
    switch(event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        v.startAnimation(shrink);
        break;
    case MotionEvent.ACTION_UP:
        v.startAnimation(grow);
        break;
    default:
        break;
    }
}

动画应定义一次并重复使用,并设置setFillAfter(true)参数;这使得绘图保持在最终位置。将动画应用于视图后,使用startAnimation()setAnimation()专为管理自己开始时间的动画而设计。

希望有帮助!