当前位置: 移动技术网 > IT编程>移动开发>Android > Android开发之手势检测及通过手势实现翻页功能的方法

Android开发之手势检测及通过手势实现翻页功能的方法

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

空气动力汽车原理,不能分手的分手歌词,windows7镜像下载

本文实例讲述了android开发之手势检测及通过手势实现翻页功能的方法。分享给大家供大家参考,具体如下:

手势是指用户手指或触摸笔在触摸屏上的连续触碰的行为,比如在屏幕上从左至右划出的一个动作,就是手势,再比如在屏幕上画出一个圆圈也是手势。手势这种连续的触碰会形成某个方向上的移动趋势,也会形成一个不规则的几何图形。android对两种手势行为都提供了支持:

1. 对于第一种手势行为而言,android提供了手势检测,并为手势检测提供了相应的监听器。

2. 对于第二种手势行为,android允许开发者添加手势,并提供了相应的api识别用户的手势。

手势检测

android 为手势检测提供了一个gesturedetector类,gestruedetector实例代表了一个手势检测器,创建gesturedetector时需要传入一个gesturedetector.ongestrurelistener实例,gesturedetector.ongestruelistener就是一个监听器,负责对用户的手势行为提供响应。

gestruedetector.ongesturelistener里包含的事件处理方法如下。

boolean ondown(motionevent e):当触碰事件按下时触发该方法。
boolean onfling(motionevent e1,motionevent e2,float velocitx,floatvelocity):当用户在触屏上拖过是触发该方法。其中velocityx,velocityy代表拖过动作在横向,纵向上的速度。
abstract void onlongpress(motionevent e):当用户在屏幕上长按时触发该方法。
boolean onscroll(motionevent e1,motionevent e2,float distance,float distance):当用户在屏幕上滚动式触发该方法。
void onshowpress(motionevent e):当用户在触摸屏上按下,而且还未移动和松开时触发该方法。
boolean onsingletapup(motionevent e):用户在触摸屏上的轻击事件将会触发该方法。

使用android的手势检测只需要两个步骤:

1. 创建一个gesturedetector.创建该对象时必须实现一个gesturedetector.ongesturelistener监听器实例。

2. 为应用程序的activity的touchevent事件绑定监听器,在事件处理中指定把activity上的touchevent事件交给gesturedetector处理。

经过上面的两个步骤之后,activity上的touchevent事件就会交给gesturedetector处理,而gesturedetector就会检测是否触发了特定的手势动作。

实例:通过手势实现翻页效果

思路:把activity的touchevent交给gesturedetector处理.这个程序的特殊之处在于,该程序使用了一个viewflipper组件,viewflipper组件其实是一个容器类组件,因此可调用addview(view v)添加多个组件,一旦向viewflipper中添加了多个组件之后,viewflipper可使用动画控制多个组件之间的切换效果。

本实例通过gesturedetector来检测用户的手势动作,并根据手势动作来控制viewflipper包含的view组件的切换,从而实现翻页效果。

关键代码如下:

public boolean onfling(motionevent event1,motionevent event2,float velocityx,velocity)
{
  if(event1.getx()-event2.getx()>flip_distance)
  {
    flipper.setinanimation(animations[0]);
    flipper.setoutanimation(animations[1]);
    flipper.showprevious();
    return true;
  }
  else if(event2.getx()-event1.getx()>flip_distance)
  {
    flipper.setinanimation(animations[2]);
    flipper.setoutanimation(animation[3]);
    flipper.shownext();
    return true;
  }
  return false;
}

其中:

animations[0]=animaionutils.loadanimation(this,r.anim.left_in);
animations[1]=animaionutils.loadanimation(this,r.anim.left_out);
animations[2]=animaionutils.loadanimation(this,r.anim.right_in);
animations[3]=animaionutils.loadanimation(this,r.anim.right_out);

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

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网