如何在Android中檢測左右和上下滑動方向?


此示例演示瞭如何在Android中檢測左右和上下滑動方向。

步驟 1 − 在Android Studio中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必要的資訊以建立新專案。

步驟 2 − 將以下程式碼新增到res/layout/activity_main.xml。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/relativeLayout"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="16dp"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="Swipe to Detect swipe Event"
      android:textSize="24sp"
      android:textStyle="bold" />
</RelativeLayout>

步驟 3 − 將以下程式碼新增到src/MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   OnSwipeTouchListener onSwipeTouchListener;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      onSwipeTouchListener = new OnSwipeTouchListener(this, findViewById(R.id.relativeLayout));
   }
   public static class OnSwipeTouchListener implements View.OnTouchListener {
      private final GestureDetector gestureDetector;
      Context context;
      OnSwipeTouchListener(Context ctx, View mainView) {
         gestureDetector = new GestureDetector(ctx, new GestureListener());
         mainView.setOnTouchListener(this);
         context = ctx;
      }
      @Override
      public boolean onTouch(View v, MotionEvent event) {
         return gestureDetector.onTouchEvent(event);
      }
      public class GestureListener extends
      GestureDetector.SimpleOnGestureListener {
         private static final int SWIPE_THRESHOLD = 100;
         private static final int SWIPE_VELOCITY_THRESHOLD = 100;
         @Override
         public boolean onDown(MotionEvent e) {
            return true;
         }
         @Override
         public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
               float diffY = e2.getY() - e1.getY();
               float diffX = e2.getX() - e1.getX();
               if (Math.abs(diffX) > Math.abs(diffY)) {
                  if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                     if (diffX > 0) {
                        onSwipeRight();
                     } else {
                        onSwipeLeft();
                     }
                     result = true;
                  }
               }
               else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                  if (diffY > 0) {
                     onSwipeBottom();
                  } else {
                     onSwipeTop();
                  }
                  result = true;
               }
            }
            catch (Exception exception) {
               exception.printStackTrace();
            }
            return result;
         }
      }
      void onSwipeRight() {
         Toast.makeText(context, "Swiped Right", Toast.LENGTH_SHORT).show();
         this.onSwipe.swipeRight();
      }
      void onSwipeLeft() {
         Toast.makeText(context, "Swiped Left", Toast.LENGTH_SHORT).show();
         this.onSwipe.swipeLeft();
      }
      void onSwipeTop() {
         Toast.makeText(context, "Swiped Up", Toast.LENGTH_SHORT).show();
         this.onSwipe.swipeTop();
      }
      void onSwipeBottom() {
         Toast.makeText(context, "Swiped Down", Toast.LENGTH_SHORT).show();
         this.onSwipe.swipeBottom();
      }
      interface onSwipeListener {
         void swipeRight();
         void swipeTop();
         void swipeBottom();
         void swipeLeft();
      }
      onSwipeListener onSwipe;
   }
}

步驟 4 − 將以下程式碼新增到androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

讓我們嘗試執行您的應用程式。我假設您已將您的實際Android移動裝置連線到您的計算機。要從Android Studio執行應用程式,請開啟專案的其中一個活動檔案,然後單擊執行  工具欄中的圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -

點選 這裡 下載專案程式碼。

更新於: 2019年11月22日

3K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告