Android手势操作示例(上/下/左/右的判断)
程序员文章站
2024-03-04 13:18:17
本文实例讲述了android手势操作方法。分享给大家供大家参考,具体如下:
android中提供了判断手势的接口,所以我们可以根据提供的api来实现各种各样的手势功能来提...
本文实例讲述了android手势操作方法。分享给大家供大家参考,具体如下:
android中提供了判断手势的接口,所以我们可以根据提供的api来实现各种各样的手势功能来提高手机应用的用户体验。
下面是我写的一段小demo:
gestureactivity.java
public class gestureactivity extends activity { private gesturedetector gesturedetector; private screen screen; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); gesturedetector = new gesturedetector(this,ongesturelistener); //得到屏幕的大小 screen = gestureutils.getscreenpix(this); } @override public boolean ontouchevent(motionevent event) { return gesturedetector.ontouchevent(event); } gesturedetector.ongesturelistener ongesturelistener = new gesturedetector.simpleongesturelistener(){ @override public boolean onfling(motionevent e1, motionevent e2, float velocityx, float velocityy) { float x = e2.getx() - e1.getx(); float y = e2.gety() - e1.gety(); //限制必须得划过屏幕的1/3才能算划过 float x_limit = screen.widthpixels / 3; float y_limit = screen.heightpixels / 3; float x_abs = math.abs(x); float y_abs = math.abs(y); if(x_abs >= y_abs){ //gesture left or right if(x > x_limit || x < -x_limit){ if(x>0){ //right show("right"); }else if(x //left show("left"); } } }else{ //gesture down or up if(y > y_limit || y < -y_limit){ if(y>0){ //down show("down"); }else if(y //up show("up"); } } } return true; } }; private void show(string value){ toast.maketext(this, value, toast.length_short).show(); } }
gestureutils.java
public class gestureutils { //获取屏幕的大小 public static screen getscreenpix(context context) { displaymetrics dm = new displaymetrics(); windowmanager windowmanager = (windowmanager) context.getsystemservice(context.window_service); windowmanager.getdefaultdisplay().getmetrics(dm); return new screen(dm.widthpixels,dm.heightpixels); } public static class screen{ public int widthpixels; public int heightpixels; public screen(){ } public screen(int widthpixels,int heightpixels){ this.widthpixels=widthpixels; this.heightpixels=heightpixels; } @override public string tostring() { return "("+widthpixels+","+heightpixels+")"; } } }
更多关于android相关内容感兴趣的读者可查看本站专题:《android文件操作技巧汇总》、《android编程开发之sd卡操作方法汇总》、《android开发入门与进阶教程》、《android资源操作技巧汇总》、《android视图view技巧总结》及《android控件用法总结》
希望本文所述对大家android程序设计有所帮助。