做者: ganzhijie 發表於 2010-09-02 15:59 原文連接 閱讀: 19 評論: 0html
Android中提供了判斷手勢的接口,全部咱們能夠根據提供的API來實現各類各樣的手勢功能來提升手機應用的用戶體驗。java
下面是我寫的一段小Demo:程序員
GestureActivity.javaide
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(){this
@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();
}spa
}orm
GestureUtils.javahtm
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+")";
}
}
}
最新新聞:
· 微軟虛擬機服務工具3.0版發佈 免費下載(2010-09-27 14:59)
· Intel悄然發佈8款新品移動處理器(2010-09-27 14:58)
· 永中Office重組內鬥:創始人或另立公司(2010-09-27 14:49)
· 《華爾街日報》科技創新獎揭曉(2010-09-27 14:39)
· Twitter計劃將廣告平臺推廣至第三方應用(2010-09-27 14:35)