如何正确使用OnTouchEvent?

时间:2018-06-12 12:16:24

标签: android ontouchlistener ontouchevent ontouch

当用户触摸屏幕的右侧或左侧时,如何使用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;
    }

}

1 个答案:

答案 0 :(得分:1)

试试这个,

 @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"/>

在“// perform here”处添加此代码以进行旋转视图(组件)

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

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

imageView.clearAnimation();