本文实例讲述了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程序设计有所帮助。
新闻热点
疑难解答