Kotlinを使ってAndroidで左右のスワイプジェスチャを処理する方法
このチュートリアルでは、Kotlinを使ってAndroidアプリで「右から左」「左から右」のスワイプジェスチャを検出し、処理する方法を解説します。
スワイプの検出には、Android標準のGestureDetectorクラスを使用します。指の動き(フリング)の移動距離と速度を判定することで、意図的なスワイプ操作だけを正確に識別できるのがポイントです。
手順1:新規プロジェクトの作成
Android Studioを開き、「File」→「New Project」を選択して、必要な項目を入力し新しいプロジェクトを作成します。
手順2:レイアウトファイル(activity_main.xml)の作成
res/layout/activity_main.xml に以下のコードを記述します。画面中央にスワイプ操作を受け付けるTextViewを配置しています。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp">
<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:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Right-to-Left and Left-to-Right swipe gestures"
android:textAlignment="center"
android:textColor="@android:color/holo_blue_light"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
手順3:MainActivity.ktの実装
src/MainActivity.kt に以下のコードを追加します。
import android.os.Bundle
import android.view.GestureDetector
import android.view.MotionEvent
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlin.math.abs
class MainActivity : AppCompatActivity(), GestureDetector.OnGestureListener {
lateinit var gestureDetector: GestureDetector
private val swipeThreshold = 100
private val swipeVelocityThreshold = 100
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
gestureDetector = GestureDetector(this)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
return if (gestureDetector.onTouchEvent(event)) {
true
}
else {
super.onTouchEvent(event)
}
}
override fun onDown(p0: MotionEvent?): Boolean {
return false
}
override fun onShowPress(p0: MotionEvent?) {
return
}
override fun onSingleTapUp(p0: MotionEvent?): Boolean {
return false
}
override fun onScroll(p0: MotionEvent?, p1: MotionEvent?, p2: Float, p3: Float): Boolean {
return false
}
override fun onLongPress(p0: MotionEvent?) {
return
}
override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
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) {
Toast.makeText(applicationContext, "Left to Right swipe gesture", Toast.LENGTH_SHORT).show()
}
else {
Toast.makeText(applicationContext, "Right to Left swipe gesture", Toast.LENGTH_SHORT).show()
}
}
}
}
catch (exception: Exception) {
exception.printStackTrace()
}
return true
}
}
コードのポイント
- onFling(): 指が画面上を素早く動かされた(フリング)ときに呼び出されるメソッドです。ここでスワイプの方向を判定します。
- diffX / diffY: タッチ開始地点(e1)と終了地点(e2)のX・Y座標の差分です。X方向の変化量がY方向より大きい場合、横方向のスワイプと判断します。
- swipeThreshold / swipeVelocityThreshold: スワイプとみなす最小移動距離(100px)と最小速度(100)です。軽いタップや微小な操作を誤検知しないための閾値として機能します。
- 判定ロジック: diffX > 0 の場合は「左から右」へのスワイプ、それ以外は「右から左」へのスワイプとしてToastで表示します。
手順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アイコン
をクリックします。接続したモバイルデバイスを選択して実行すると、端末にアプリの画面が表示されます。
画面上で左右にスワイプすると、方向に応じて「Left to Right swipe gesture」または「Right to Left swipe gesture」というトーストメッセージが表示されれば成功です。


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