Android–手勢識別之GestrueDetector

來源:互聯網
上載者:User

在使用android手機中經常會碰到很多做得很炫效果的應用,比如手指在螢幕上向左或者向右滑動進行介面切換的效果。這其實是用到了一個叫GestureDetector的對象Gesture:手勢 做手勢、Detector:監聽 偵測器。其實就是通過計算從接觸螢幕到離開螢幕過程中xy軸位移,和移動的速度而進行判斷做出後續的動作。

對一個控制項實現手勢識別中滑動的監聽(還有單擊、雙擊、長按等等就沒介紹了)有三個步驟:1、建立一個類DefaultGestureDetector繼承自SimpleOnGestureListener重寫onFling事件2、執行個體化一個手勢識別對象GestureDetector gd=new GestrueDetector(new DefaultGestureDetector());3、重寫控制項的onTouchEvent()事件(Activity直接Override,控制項就setOnTouchListener())

第一步:

    class DefaultGestureDetector extends SimpleOnGestureListener{
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY){
final int FLING_MIN_DISTANCE=100;//X或者y軸上移動的距離(像素)
final int FLING_MIN_VELOCITY=200;//x或者y軸上的移動速度(像素/秒)
if((e1.getX()-e2.getX())>FLING_MIN_DISTANCE && Math.abs(velocityX)>FLING_MIN_VELOCITY)
Toast.makeText(Main.this, "向左滑動", Toast.LENGTH_SHORT).show();
else if((e2.getX()-e1.getX())>FLING_MIN_DISTANCE && Math.abs(velocityX)>FLING_MIN_VELOCITY)
Toast.makeText(Main.this, "向右滑動", Toast.LENGTH_SHORT).show();
return false;
}
}

上面的e1.getX()-e2.getX()是計算x軸上移動的距離velocityx:x軸上的移動速率

第二部:

    private GestureDetector gestureDetector;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gestureDetector=new GestureDetector(new DefaultGestureDetector());

}

第三部:

    @Override
public boolean onTouchEvent(MotionEvent event){
return gestureDetector.onTouchEvent(event);
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.