简体   繁体   中英

Android onTouch animation removed on ACTION_UP

This should be fairly simple, but it is turning out to be more complicated than I thought. How can I apply a ScaleAnimation to a view and get it to stay for the entire duration of a finger press? In other words, while he finger is down shrink the view until the finger is removed, then return it to its original size? This is what I have tried:

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

If I apply setFillEnabled(true) and setFillAfter(true) then the shrink stays indefinitely. If I don't use it it shrinks for a second then goes back to normal. Thanks ahead of time

You forgot the 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!
    }
}

It's a bit unclear what you have and haven't tried in what combination, so here's an example that works:

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;
    }
}

The animations should be defined once and reused, with their setFillAfter(true) parameter set; this makes the drawing stick in the final position. When you apply the animations to the view use startAnimation() , setAnimation() is designed for animations that manage their own start times.

Hope that Helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM