首页 > 解决方案 > 如何在 Android Studio 中连续移动对象

问题描述

按住按钮时如何在Android Studio中连续移动ImageView,但不再单击时停止?换句话说:如何检测按钮是否“未点击”或直接检测它是否被按住。感谢您的帮助

标签: javaandroidbuttonimageview

解决方案


要检测按钮是否被按下/释放(向下/向上),使用 TouchListener。

    imageView = findViewById(R.id.image);
    button = findViewById(R.id.button);
    root_layout = findViewById(R.id.root_layout); //parent layout

    final Handler handler = new Handler();
    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            float x = imageView.getX();
            if(x > root_layout.getWidth())
                x = 0;
            else
                x += 6; //Increase value of '6' to move the imageView faster
            imageView.setX(x);

            handler.postDelayed(this,0); //increase delay '0' if facing lag. 
            // This is the rate at which the x value of our imageView is being updated
            
        }
    };

    button.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    handler.post(runnable); //Start moving imageView
                    break;
                case MotionEvent.ACTION_UP:
                    handler.removeCallbacks(runnable); //Stop moving imageView
                    break;
            }
        return true;
        }
    });


推荐阅读