Android提供了特殊類型的觸摸屏事件,如掐,雙擊,滾動(dòng),長(zhǎng)按和退縮。這些都被稱為手勢(shì)。
Android提供GestureDetector類接收移動(dòng)事件,并告訴我們,這些事件是否有對(duì)應(yīng)手勢(shì)。要使用它,需要?jiǎng)?chuàng)建GestureDetector對(duì)象,然后擴(kuò)展另一個(gè)類GestureDetector.SimpleOnGestureListener充當(dāng)監(jiān)聽器,并覆蓋一些方法。它的語法如下:
GestureDetector myG; myG = new GestureDetector(this,new Gesture()); class Gesture extends GestureDetector.SimpleOnGestureListener{ public boolean onSingleTapUp(MotionEvent ev) { } public void onLongPress(MotionEvent ev) { } public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { } public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { } } }
Android提供ScaleGestureDetector類來處理如:捏等手勢(shì)。為了使用它,需要實(shí)例化這個(gè)類的一個(gè)對(duì)象。它的語法如下:
ScaleGestureDetector SGD; SGD = new ScaleGestureDetector(this,new ScaleListener());
第一個(gè)參數(shù)是上下文,第二個(gè)參數(shù)是事件偵聽器。必須定義事件偵聽器并覆蓋 onTouchEvent 函數(shù),使其工作。它的語法如下:
public boolean onTouchEvent(MotionEvent ev) { SGD.onTouchEvent(ev); return true; } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScale(ScaleGestureDetector detector) { float scale = detector.getScaleFactor(); return true; } }
除了捏手勢(shì),還有其它方法 avaialible 通知的詳細(xì)信息的觸摸事件。它們?nèi)缦拢?/p>
| Sr.No | Method & description |
|---|---|
| 1 |
getEventTime() 此方法得到正被處理的當(dāng)前事件的事件時(shí)間.. |
| 2 |
getFocusX() 這種方法得到的X坐標(biāo)當(dāng)前手勢(shì)的焦點(diǎn) |
| 3 |
getFocusY() 這個(gè)方法得到當(dāng)前手勢(shì)的焦點(diǎn)的Y坐標(biāo) |
| 4 |
getTimeDelta() 此方法返回在先前接受縮放事件和當(dāng)前縮放事件之間的毫秒的時(shí)間差 |
| 5 |
isInProgress() 如果刻度手勢(shì)正在進(jìn)行此方法返回true.. |
| 6 |
onTouchEvent(MotionEvent event) 此方法接受MotionEvents并調(diào)度事件在適當(dāng)?shù)臅r(shí)候 |
這里有一個(gè)例子演示如何使用ScaleGestureDetector類。它創(chuàng)建了一個(gè)基本的應(yīng)用程序,放大和捏縮小。
為了試驗(yàn)這個(gè)例子,可以在實(shí)際設(shè)備或仿真器,觸摸屏啟用運(yùn)行此程序。
| Steps | 描述 |
|---|---|
| 1 | 使用Android Studio創(chuàng)建Android應(yīng)用程序,并將它命名為:Gestures。在創(chuàng)建這個(gè)項(xiàng)目,確保目標(biāo)SDK編譯在Android SDK的最新版本和使用更高級(jí)別的API |
| 2 | 修改src/MainActivity.java文件添加必要的代碼 |
| 3 | 修改res/layout/activity_main添加相應(yīng)的XML組件 |
| 4 | 修改res/values/string.xml 添加必要的字符串 |
| 5 | 運(yùn)行應(yīng)用程序并選擇運(yùn)行Android的設(shè)備,并在其上安裝的應(yīng)用和驗(yàn)證結(jié)果 |
以下是修改后的主活動(dòng)文件的內(nèi)容 src/com.yiibai.gestures/MainActivity.java.
package com.example.gestures; import android.app.Activity; import android.graphics.Matrix; import android.os.Bundle; import android.view.Menu; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.widget.ImageView; public class MainActivity extends Activity { private ImageView img; private Matrix matrix = new Matrix(); private float scale = 1f; private ScaleGestureDetector SGD; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); img = (