How do I get an image view to continually move across the screen when a button is held down?

时间:2015-12-19 12:24:37

标签: java android button imageview

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 个答案:

答案 0 :(得分:3)

将您的触控侦听器视为状态机。发生ACTION_DOWN事件时,开始执行您想要执行的任何操作。发生ACTION_UP / ACTION_CANCEL事件时停止您的操作。那么你如何实现这个呢?

你的州旗可以是一个简单的布尔值:

boolean shouldCharacterMove = false;

为视图定义触控侦听器。

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

在我们定义setShouldCharacterMove之前,我们需要找出一种移动项目的方法。我们可以通过在X毫秒之后运行的Runnable来完成此任务。

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

现在我们可以定义setShouldCharacterMove

void setShouldCharacterMove(boolean shouldMove) {
    shouldCharacterMove = shouldMove;
    IV_player.removeCallbacks(characterMoveRunnable);
    if (shouldMove) {
        IV_player.post(characterMoveRunnable);
    }
}