如何正确使用OnTouchEvent?

How to use OnTouchEvent Correctly?

当用户触摸屏幕的右侧或左侧时,如何使用 OnTouchEvent 函数使 ImageView 向右或向左移动?下面的代码是我试过的。我可以做些什么来改进它并使其发挥作用?

ImageView circle1 = (ImageView) findViewById(R.id.circle1);

public boolean onTouchEvent(MotionEvent MotionEvent motionEvent;
        motionEvent){

    switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {

        // Player has touched the screen
        case MotionEvent.ACTION_DOWN:

            if (motionEvent.getY() > screenHeight - screenWidth / 8) {
                circleIsMovingRIGHT = true;
                circleIsMovingLEFT = false;
            } else {
                circleIsMovingRIGHT = false;
                circleIsMovingLEFT = true;
            }
            break;
        }
        return true;
    }

}

试试这个,

 @SuppressLint("ClickableViewAccessibility")
        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);

          anyView.setOnTouchListener(this);
       }


 @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()) {
            case R.id.anyView:
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    // perform here
                }
                break;
        }
        return false;
    }

在res/anim/rotate中添加此代码。xml

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

在旋转视图(组件)的“//此处执行”处添加此代码

imageView.startAnimation(AnimationUtils.loadAnimation(context,R.anim.rotate));

如果您使用 android:repeatCount="infinite" 那么您将动态停止旋转,在特定条件下应用此代码

imageView.clearAnimation();