初识GestureDetector

设计思路,步骤,方法

1.获取当前MotionEvent对象
2.mGestureDetector.onTouchEvent(event);利用GestureDetector对象调用onTouchEvent()方法把event对象传给GestureListener
3.继承监听器SimpleOnGestureListener 里面包含了两个接口,调用onfling()方法进行手势滑动的识别

我们先做一下准备工作
这是我们的手势识别载体,所有在这上面的手势才能识别因为在activity中设置的是miv.setOnTouchListener();

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

在activity中初始化 imageview

 miv = (ImageView) findViewById(R.id.imageView1);

然后进行第一步,第二步操作

  miv.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                //这是第二部操作
                mGestureDetector.onTouchEvent(event);
                return true;
            }
        });

接下来进行第三步操作、

class mSimleGestureListener extends SimpleOnGestureListener{
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {
            // TODO Auto-generated method stub
            if(e1.getX()-e2.getX()>50){
                Toast.makeText(getApplicationContext(), "从右向左滑的手势", Toast.LENGTH_SHORT).show();
            }else if(e2.getX()-e1.getX()>50){
                Toast.makeText(getApplicationContext(), "从左向右滑的手势", Toast.LENGTH_SHORT).show();
            }
            return super.onFling(e1, e2, velocityX, velocityY);
        }
    }

是否还记得GestureDetector还没初始化,因为初始化要传一个SimpleOnGestureListener对象的参数,那么在oncreate()方法里面添加

mGestureDetector = new GestureDetector(new mSimleGestureListener());

注意:整个这样的方法有缺陷,就是打一个全回到离原点没超过50像素的话,就会当作没有移动至50像素以外的地方,所以没反应。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值