DavidTonarini
DavidTonarini

Reputation: 951

Android: how to know if button is held down

I am playing with a game on Android, and I have a function MoveCharacter (int direction) that moves an animated sprite when buttons are pressed

For example, when user presses up I have this code:

 mControls.UpButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mLevel.mCharAnimation.FrameUp();
            }           
        });

However, I’d like to be able to keep moving the character as long as the user keeps the button down. Surprisingly, I have not found out how to do this in Android. Is there some kind of onButtonDownLister?

Upvotes: 7

Views: 10976

Answers (4)

Daniel Storm
Daniel Storm

Reputation: 18898

As mentioned in the comments by Gary Bak you would want to detect if the user drags their finger outside the button also.

mButton.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // Pressed down
                return true;
            case MotionEvent.ACTION_UP:
                // Released
                return true;
            case MotionEvent.ACTION_CANCEL:
                // Released - Dragged finger outside
                return true;
        }
        return false;
    }
});

Upvotes: 4

Lawrence Choy
Lawrence Choy

Reputation: 6108

You can use OnTouchListener instead

mControls.UpButton.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:
                    mLevel.mCharAnimation.FrameUp();
                    break;
                case MotionEvent.ACTION_UP:
                    // User released the button, do your stuff here
                    break;
                }
                return false;

            }           
        });

Upvotes: 0

PearsonArtPhoto
PearsonArtPhoto

Reputation: 39698

You want onTouchListener(). Basically, this will allow you to see when the object is touched, see how the user is moving their finger, and know when the let go.

Upvotes: 0

Sam
Sam

Reputation: 86948

You need to use an OnTouchListener to have separate actions for down, up, and other states.

mControls.UpButton.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            // Do something
            return true;
        case MotionEvent.ACTION_UP:
            // No longer down
            return true;
        }
        return false;
    }
});

Upvotes: 24

Related Questions