2

I have searched high and low for an answer to this and can't find one anywhere that works.

For my university assignment i need to create an adventure game in android studio. I want it so when I click down and hold an arrow button (so in the case given its the up button), that the ImageView (player) will continually move across the screen until I release the button. Ive tried OnTouchListeners and mouse events using ACTION_UP and ACTION_DOWN and that works but not for what i need as it still only moves one step when clicked.

        ImageView IV_player;
        Button ButtonUp;

        IV_player = (ImageView) findViewById(R.id.IV_player); 
        ButtonUp = (Button) findViewById(R.id.ButtonUp);       

        ButtonUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            IV_player.setY(IV_player.getY() - 32);

        }
    });
  • 1
    try http://stackoverflow.com/questions/29433468/problems-changing-the-position-of-an-imageview-in-android http://stackoverflow.com/a/3442189/3209739 and there are many posts. – cgr Dec 19 '15 at 12:46

1 Answers1

3

Treat your touch listener like a state machine. When an ACTION_DOWN event occurs, start doing whatever action you want to do. When an ACTION_UP/ACTION_CANCEL event occurs stop your action. So how do you go about implementing this?

Your state flag can be a simple boolean:

boolean shouldCharacterMove = false;

Define your touch listener for the view.

ButtonUp.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getActionMasked()) {
                case MotionEvent.ACTION_DOWN:
                    setShouldCharacterMove(true);
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    setShouldCharacterMove(false);
                    break;
            }
            return true;
        }
});

Before we define setShouldCharacterMove we need to figure out a way to move items. We can do this through a Runnable that runs after X milliseconds.

private final Runnable characterMoveRunnable = new Runnable() {
    @Override
    public void run() {
        float y = IV_player.getTranslationY();
        IV_player.setTranslationY(y + 5); // Doesn't have to be 5.

        if (shouldCharacterMove) {
            IV_player.postDelayed(this, 16); // 60fps
        }
    }
};

Now we can define setShouldCharacterMove:

void setShouldCharacterMove(boolean shouldMove) {
    shouldCharacterMove = shouldMove;
    IV_player.removeCallbacks(characterMoveRunnable);
    if (shouldMove) {
        IV_player.post(characterMoveRunnable);
    }
}
asadmshah
  • 1,338
  • 9
  • 7