GestureDetector--手势识别初体验(一)

来源:互联网 发布:德国读研一年费用知乎 编辑:程序博客网 时间:2024/05/15 10:30

这里写图片描述

双击爆炸;右向左滑动←;左向右滑动→;
MainActivity.class

package com.superxingyun.gestruedetectordemo;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.GestureDetector;import android.view.GestureDetector.SimpleOnGestureListener;import android.view.MotionEvent;import android.view.View;import android.widget.ImageView;import android.widget.Toast;public class MainActivity extends AppCompatActivity {    ImageView img;    GestureDetector gestureDetector;    class MyGestureListen extends SimpleOnGestureListener{        @Override//滑动事件        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {            if (e1.getX() - e2.getX() > 50){                Toast.makeText(MainActivity.this, "←←←←←←←←←←", Toast.LENGTH_SHORT).show();            }else if (e2.getX() - e1.getX() >50){                Toast.makeText(MainActivity.this, "→→→→→→→→→→", Toast.LENGTH_SHORT).show();            }            return super.onFling(e1, e2, velocityX, velocityY);        }     /*   @Override//单击事件        public boolean onDown(MotionEvent e) {            Toast.makeText(MainActivity.this, "...........", Toast.LENGTH_SHORT).show();            return super.onDown(e);        }*/        @Override//双击事件        public boolean onDoubleTap(MotionEvent e) {            Toast.makeText(MainActivity.this, "BOOM", Toast.LENGTH_SHORT).show();            return super.onDoubleTap(e);        }    }    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        gestureDetector = new GestureDetector(MainActivity.this, new MyGestureListen());        img = (ImageView) findViewById(R.id.img);        img.setOnTouchListener(new View.OnTouchListener() {            @Override//可以捕获到触摸屏幕发生的Event事件            public boolean onTouch(View vew, MotionEvent motionEvent) {                gestureDetector.onTouchEvent(motionEvent);                return true;            }        });    }}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.superxingyun.gestruedetectordemo.MainActivity">    <ImageView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        app:srcCompat="@mipmap/i"        android:layout_centerVertical="true"        android:id="@+id/img" /></RelativeLayout>
0 0
原创粉丝点击