2011-06-03 51 views
2

这应该相当简单,但事实证明比我想象的要复杂。我如何将一个ScaleAnimation应用到视图并让它在手指按压的整个过程中保持不变?换句话说,当他的手指向下收缩视图直到手指被移除,然后将其恢复到原来的大小? 这是我曾尝试:Android onTouch动画在ACTION_UP上删除

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

这是一个有点不清楚你有什么和什么样的组合还没有尝试过,所以这里是工作的例子:

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()专为管理其自己的开始时间的动画而设计。

希望有助于!

+0

工程就像一个魅力,除了我需要返回true onTouch,否则动画将不会恢复正常。谢谢 – Tom 2011-06-04 22:11:54

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! 
    } 
} 
+0

我觉得'v.startAnimation(shrinkAnim)';而不是'v.setAnimation()'...? – Houcine 2011-06-03 02:01:35

+0

感谢您的指针,但即使在休息时,如果我使用fillEnabled,视图仍然会缩小,并且如果我不使用fillEnabled,则持续几秒钟。 – Tom 2011-06-03 02:45:22

+0

@TOM:ad'setFillAfter(true)'给你的动画并且检查 – Houcine 2011-06-03 02:55:33