【问题标题】: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
【问题描述】:

我已经到处搜索了这个问题的答案,但在任何地方都找不到有效的答案。

对于我的大学作业,我需要在 android studio 中创建一个冒险游戏。我想要它,所以当我单击并按住一个箭头按钮(因此在给定向上按钮的情况下)时,ImageView(播放器)将不断在屏幕上移动,直到我释放按钮。我已经尝试过使用 ACTION_UP 和 ACTION_DOWN 的 OnTouchListeners 和鼠标事件,这很有效,但不适用于我需要的,因为它在单击时仍然只移动一步。

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

        }
    });

【问题讨论】:

标签: java android button imageview


【解决方案1】:

将您的触摸监听器视为状态机。当一个 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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多