亲宝软件园·资讯

展开

Android手势操作 Android手势操作示例(上/下/左/右的判断)

ztp800201 人气:0
想了解Android手势操作示例(上/下/左/右的判断)的相关内容吗,ztp800201在本文为您仔细讲解Android手势操作的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,手势操作,下面大家一起来学习吧。

本文实例讲述了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程序设计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论