Imageview动画从滑动手势开始

时间:2020-08-19 05:37:17

标签: android kotlin animation imageview swipe

我在这里浏览了其他问题,但是似乎没有人问过我。我希望能够通过向上滑动硬币来翻转硬币(用于imageview的图像)。我已经将动画编码为一个按钮,但是希望能够将相同的代码添加到滑动中,以便为用户提供任一选项。该怎么办?

1 个答案:

答案 0 :(得分:1)

您必须使用OnTouchListener和GestureDetector

这里是一个例子:

package com.example.androidlayout;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ImageView iv = (ImageView) findViewById(R.id.imageview);
        final GestureDetector mDetector = new GestureDetector(MainActivity.this, new GestureListener());
        iv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mDetector.onTouchEvent(event);
                return true;
            }
        });
    }

    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;

    private class GestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                // Right to left
                return false;
            }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                // Left to right
                return false;
            }
            if(e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                // Bottom to top
                //Your code to flip the coin
                Log.println(Log.VERBOSE,"Coin", "Coin flipped");
                return false;
            }  else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                // Top to bottom
                return false;
            }
            return false;
        }

    }
}

我已经在模拟器上对其进行了测试,并且效果很好。