2011-06-03 38 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