您的位置:首页 > 移动开发 > Android开发

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

2016-09-27 10:24 190 查看




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

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息