OnGestureListener()
แบบต่างๆ
onDown()
– เกิดขึ้นเมื่อมีการสัมผัสจอภาพonFling()
– เกิดขึ้นเมื่อมีการสัมผัสจอภาพและลากonLongPress()
– เกิดขึ้นเมื่อมีการสัมผัสจอภาพค้างไว้onScroll()
– เกิดขึ้นเมื่อมีการลากนิ้ว เพื่อเลื่อนออบเจ็กต์ต่างๆonShowPress()
– เกิดขึ้นเมื่อมีการสัมผัสจอภาพ แต่ยังไม่มีการลากหรือปล่อยนิ้วonSingleTapUp()
– เกิดขึ้นเมื่อมีการปล่อยน้ิว
ในตัวอย่างนี้ใข้ onFling()
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Fling right, left, up, or down\n" android:textSize="18sp" /> </LinearLayout> |
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
package com.phaisarn.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.GestureDetector; import android.view.MotionEvent; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private static final int IF_MOVE = 50; private GestureDetector gestureDetector; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (e1.getY() - e2.getY() > IF_MOVE) { textView.append("\nFling Up with velocity " + velocityY); } else if (e2.getY() - e1.getY() > IF_MOVE) { textView.append("\nFling Down with velocity " + velocityY); } else if (e1.getX() - e2.getX() > IF_MOVE) { textView.append("\nFling Left with velocity " + velocityX); } else if (e2.getX() - e1.getX() > IF_MOVE) { textView.append("\nFling Right with velocity " + velocityX); } return false; } }); } @Override public boolean onTouchEvent(MotionEvent event) { return gestureDetector.onTouchEvent(event); } } |