1

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

4

2 回答 2

1

要检测按钮是否被按下/释放(向下/向上),使用 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;
        }
    });

于 2020-06-20T20:10:53.813 回答
0

试试这个解决方案

第 1 步:- 需要在 res 文件夹中定义 anim 文件夹。

现在将 rotate.xml 文件放在 anim 文件夹中。

rotate.xml文件

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <rotate android:fromDegrees="0"
        android:toDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="600"
        android:repeatMode="restart"
        android:repeatCount="infinite"
        android:interpolator="@android:anim/cycle_interpolator"/>

</set>

第 2 步:- 以编程方式声明动画

// Animation
    Animation animFadein;

in onCreate()
// load the animation
        animFadein = AnimationUtils.loadAnimation(getApplicationContext(),
                R.anim.rotate);

第 3 步:- 像这样检测用户触摸以启动和停止动画

button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            //start animation here
           imageView.startAnimation(animFadein);
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            // stop animation here
             imageView.stopAnimation(animFadein);
        }
        return true;
    }
});
于 2020-06-20T17:59:44.117 回答