当前位置: 移动技术网 > 移动技术>移动开发>Android > Android View进行手势识别详解

Android View进行手势识别详解

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

       我们在进行android游戏开发时会用到很多种控制,包括前面讲到的按键和轨迹球控制方式,除此之外还有手势操作、重力感应等多种控制方式需要了解掌握。本节主要为大家讲解在view中如何进行手势识别。

       很多网友发现android中手势识别提供了两个类,由于android 1.6以下的版本比如cupcake中无法使用android.view.gesturedetector,而android.gesture.gesture是android 1.6开始支持的,考虑到仍然有使用android 1.5固件的网友,就来看下兼容性更强的android.view.gesturedetector。在android.view.gesturedetector类中有很多种重载版本,下面我们仅提到能够自定义在view中的两种方法,分别为gesturedetector(context context, gesturedetector.ongesturelistener listener) 和gesturedetector(context context, gesturedetector.ongesturelistener listener, handler handler) 。我们可以看到第一个参数为context,所以我们想附着到某view时,最简单的方法就是直接从超类派生传递context,实现gesturedetector里中提供一些接口。

       下面我们就以实现手势识别的onfling动作,在cwjview中我们从view类继承,当然大家可以从textview等更高层的界面中实现触控。

java代码

class cwjview extends view {  
 
  private gesturedetector mgd;  
  public cwjview(context context, attributeset attrs) {  
    super(context, attrs);  
     
    mgd = new gesturedetector(context, new gesturedetector.simpleongesturelistener() {  
        public boolean onfling(motionevent e1, motionevent e2, float velocityx, float velocityy) {  
          int dx = (int) (e2.getx() - e1.getx()); //计算滑动的距离  
 
          if (math.abs(dx) > major_move && math.abs(velocityx) > math.abs(velocityy)) { //降噪处理,必须有较大的动作才识别  
            if (velocityx > 0) {  
              //向右边  
 
            } else {  
              //向左边  
 
            }  
            return true;  
          } else {  
            return false; //当然可以处理velocityy处理向上和向下的动作  
          }  
        }  
      });  
  }  
 
 /*提示大家上面仅仅探测了fling动作仅仅实现了onfling方法,这里相关的还有以下几种方法来实现具体的可以参考我们以前的文章有详细的解释: 
 
 boolean ondoubletap(motionevent e)  
 boolean ondoubletapevent(motionevent e)  
 boolean ondown(motionevent e)  
 void onlongpress(motionevent e)  
 boolean onscroll(motionevent e1, motionevent e2, float distancex, float distancey)  
 void onshowpress(motionevent e)  
 boolean onsingletapconfirmed(motionevent e)  
 boolean onsingletapup(motionevent e)  
 */ 
 
  //接下来是重点,让我们的view接受触控,需要使用下面两个方法让gesturedetector类去处理ontouchevent和onintercepttouchevent方法。  
 
  @override 
  public boolean ontouchevent(motionevent event) {   
    mgd.ontouchevent(event);  
    return true;  
  }  
 
  @override 
  public boolean onintercepttouchevent(motionevent event) {  
    return mgd.ontouchevent(event);  
  }  
 
} 

       本节关于view中手势识别的内容就讲这些。大家知道,很多android设备都提供了重力感应器和加速度感应器,而稍好些的设备还具备陀螺仪感应器,提供测试角速度功能。下一节将为大家讲解重力感应知识。

       以上就是对android view进行的手势识别的资料整理,谢谢大家对本站的支持,后续继续补充相关资料。

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

相关文章:

验证码:
移动技术网