当前位置: 移动技术网 > 移动技术>移动开发>Android > Android编程使用GestureDetector实现简单手势监听与处理的方法

Android编程使用GestureDetector实现简单手势监听与处理的方法

2019年07月24日  | 移动技术网移动技术  | 我要评论

本文实例讲述了android编程使用gesturedetector实现简单手势监听与处理的方法。分享给大家供大家参考,具体如下:

添加手势识别监听步骤:

一、给相应的控件添加触摸监听事件,

二、利用gesturedetector转发这个触摸事件。

三、事先定义好一个实现simpleongesturelistener这个监听的接口的类

四、在这个监听中处理各种事件。

具体代码如下:

mainactivity代码如下:

package com.example.gesturedetector;
import android.support.v7.app.appcompatactivity;
import android.os.bundle;
import android.view.gesturedetector;
import android.view.motionevent;
import android.view.view;
import android.widget.imageview;
import android.widget.toast;
public class mainactivity extends appcompatactivity {
   imageview img;
  gesturedetector mygesturedetector;
  class mygesturelistener extends gesturedetector.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_long).show();
      }else if(e2.getx()-e1.getx()>50){
        toast.maketext(mainactivity.this,"从左往右滑动",toast.length_long).show();
      }
      return super.onfling(e1, e2, velocityx, velocityy);
    }
  }
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    img = (imageview) findviewbyid(r.id.img);
    mygesturedetector = new gesturedetector(new mygesturelistener());
    img.setontouchlistener(new view.ontouchlistener() {
      //motionevent可以捕捉我们触摸屏幕的event事件
      @override
      public boolean ontouch(view view, motionevent motionevent) {
        mygesturedetector.ontouchevent(motionevent);
        return true;
      }
    });
  }
}

activity_main的代码如下:

<?xml version="1.0" encoding="utf-8"?>
<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"
  android:paddingbottom="@dimen/activity_vertical_margin"
  android:paddingleft="@dimen/activity_horizontal_margin"
  android:paddingright="@dimen/activity_horizontal_margin"
  android:paddingtop="@dimen/activity_vertical_margin"
  tools:context="com.example.gesturedetector.mainactivity">
  <imageview
    android:id="@+id/img"
    android:src="@mipmap/ic_launcher"
    android:layout_centerhorizontal="true"
    android:layout_centervertical="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</relativelayout>

更多关于android相关内容感兴趣的读者可查看本站专题:《android手势操作技巧汇总》、《android基本组件用法总结》、《android开发入门与进阶教程》、《android调试技巧与常见问题解决方法汇总》、《android视图view技巧总结》、《android布局layout技巧总结》及《android控件用法总结

希望本文所述对大家android程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网