Android
 Computer >> コンピューター >  >> プログラミング >> Android

KotlinでAndroidのスワイプ方向(左右・上下)を検出する方法を徹底解説

はじめに

本記事では、Kotlinを使用してAndroidアプリでスワイプ操作の方向(左・右・上・下)を検出する方法を、実際のコード例とともに解説します。GestureDetectorクラスを活用すれば、ユーザーのフリング(スワイプ)ジェスチャーを簡単に判別できます。

実装手順

ステップ1:新規プロジェクトを作成する

Android Studioで新しいプロジェクトを作成します。メニューから「File → New Project」を選択し、必要な情報をすべて入力してプロジェクトを作成してください。

ステップ2:レイアウトファイルにコードを追加する

res/layout/activity_main.xmlに以下のコードを追加します。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:background="#008080"
        android:padding="5dp"
        android:text="TutorialsPoint"
        android:textColor="#fff"
        android:textSize="24sp"
        android:textStyle="bold" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Swipe to Detect swipe Event"
        android:textAlignment="center"
        android:textColor="@android:color/holo_purple"
        android:textSize="24sp"
        android:textStyle="bold" />
</RelativeLayout>

ステップ3:MainActivity.ktにコードを追加する

src/MainActivity.ktに以下のコードを追加します。内部クラスOnSwipeTouchListenerを作成し、GestureDetectorによってスワイプイベントを検出する仕組みです。

import android.content.Context
import android.os.Bundle
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlin.math.abs
class MainActivity : AppCompatActivity() {
    var onSwipeTouchListener: OnSwipeTouchListener? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        onSwipeTouchListener = OnSwipeTouchListener(this, findViewById(R.id.relativeLayout))
    }
    class OnSwipeTouchListener internal constructor(ctx:Context, mainView: View):View.OnTouchListener{
        private val gestureDetector: GestureDetector
        private var context: Context
        private lateinit var onSwipe:OnSwipeListener
        init{
            gestureDetector = GestureDetector(ctx, GestureListener())
            mainView.setOnTouchListener(this)
            context = ctx
        }
        override fun onTouch(v:View, event: MotionEvent):Boolean {
            return gestureDetector.onTouchEvent(event)
        }
        private companion object {
            private const val swipeThreshold = 100
            private const val swipeVelocityThreshold = 100
        }
        inner class GestureListener:GestureDetector.SimpleOnGestureListener() {
            override fun onDown(e:MotionEvent):Boolean {
                return true
            }
            override fun onFling(e1:MotionEvent, e2:MotionEvent, velocityX:Float, velocityY:Float):Boolean {
                var result = false
                try{
                    val diffY = e2.y - e1.y
                    val diffX = e2.x - e1.x
                    if (abs(diffX) > abs(diffY)){
                        if (abs(diffX) > swipeThreshold && abs(velocityX) > swipeVelocityThreshold){
                            if (diffX > 0){
                                onSwipeRight()
                            }
                            else{
                                onSwipeLeft()
                            }
                            result = true
                        }
                    }
                    else if (abs(diffY) > swipeThreshold && abs(velocityY) > swipeVelocityThreshold){
                        if (diffY > 0){
                            onSwipeBottom()
                         }
                        else{
                            onSwipeTop()
                         }
                        result = true
                    }
                }
                catch (exception:Exception) {
                    exception.printStackTrace()
                }
                return result
            }
        }
        internal fun onSwipeRight() {
            Toast.makeText(context, "Swiped Right", Toast.LENGTH_SHORT).show()
            this.onSwipe.swipeRight()
        }
        internal fun onSwipeLeft() {
            Toast.makeText(context, "Swiped Left", Toast.LENGTH_SHORT).show()
            this.onSwipe.swipeLeft()
        }
        internal fun onSwipeTop() {
            Toast.makeText(context, "Swiped Up", Toast.LENGTH_SHORT).show()
            this.onSwipe.swipeTop()
        }
        internal fun onSwipeBottom() {
            Toast.makeText(context, "Swiped Down", Toast.LENGTH_SHORT).show()
            this.onSwipe.swipeBottom()
        }
        internal interface OnSwipeListener {
            fun swipeRight()
            fun swipeTop()
            fun swipeBottom()
            fun swipeLeft()
        }
    }
}

ステップ4:AndroidManifest.xmlを編集する

androidManifest.xmlに以下のコードを追加します。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.q11">
    <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でプロジェクト内の任意のアクティビティファイルを開き、ツールバーの「Run」KotlinでAndroidのスワイプ方向(左右・上下)を検出する方法を徹底解説アイコンをクリックしてください。表示された候補から接続中のモバイルデバイスを選択すると、端末にアプリの初期画面が表示されます。

KotlinでAndroidのスワイプ方向(左右・上下)を検出する方法を徹底解説

KotlinでAndroidのスワイプ方向(左右・上下)を検出する方法を徹底解説

コードのポイント

  • onFling()のオーバーライド:GestureDetector.SimpleOnGestureListeneronFling()メソッドを利用することで、スワイプの開始地点(e1)と終了地点(e2)、そして指の移動速度を取得できます。
  • 方向の判定ロジック:X軸方向の移動量(diffX)とY軸方向の移動量(diffY)を比較し、絶対値が大きい方を主なスワイプ方向として判定します。diffXが正なら右スワイプ、diffYが正なら下スワイプとなります。
  • しきい値による誤検知防止:swipeThreshold(100)とswipeVelocityThreshold(100)を設けることで、意図しない軽微なタッチ操作をスワイプとして誤認識しないように制御しています。
  • 柔軟な拡張性:スワイプ検出時にはToastで方向を通知するとともに、OnSwipeListenerインターフェースを通じて各方向ごとの独自処理を呼び出せる設計になっているため、画面遷移やデータ更新などへの応用も容易です。
  1. Androidで右から左へのスワイプジェスチャを検出・処理する方法

    はじめにこのチュートリアルでは、Androidアプリにおいて右から左へのスワイプジェスチャを検出して処理する方法を解説します。今回紹介する実装は汎用性が高く、上下左右どの方向のスワイプにも対応できる仕組みになっています。GestureDetector を活用したカスタムタッチリスナーを作成し、ステップごとにサンプルコードを見ながら進めていきましょう。手順1:新しいプロジェクトを作成するAndroid Studioを起動し、メニューから File ⇒ New Project を選択して、必要な項目を入力しながら新しいプロジェクトを作成します。手順2:レイアウトファイル(activity_main

  2. 【Android】左右・上下のスワイプ方向を検出する実装方法を解説

    Androidでスワイプ方向(左・右・上・下)を検出するには? この記事では、AndroidアプリにおいてGestureDetectorを使用し、ユーザーが画面をスワイプした方向(左・右・上・下)を検出して判定する方法を、ステップごとにわかりやすく解説します。 スワイプ操作は、画像の切り替えやリストの削除など、モダンなアプリでは欠かせないUIパターンです。本サンプルを実装すれば、4方向すべてのスワイプイベントを簡単にハンドリングできるようになります。 ステップ1:新規プロジェクトを作成する まず、Android Studioを起動し、メニューから「File → New Project」を選択