이 튜토리얼에서는 Kotlin을 사용해 안드로이드 앱에서 좌/우 및 상/하 스와이프 방향을 감지하는 방법을 단계별로 알아봅니다. GestureDetector를 활용하면 사용자의 플링(Fling) 제스처를 손쉽게 인식할 수 있습니다.
1단계: 새 프로젝트 생성
Android Studio에서 File → New Project를 선택하고, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다. 언어는 반드시 Kotlin으로 설정하세요.
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>레이아웃은 루트로 RelativeLayout을 사용하며, 화면 중앙에 "Swipe to Detect swipe Event"라는 안내 문구가 표시됩니다.
3단계: MainActivity.kt 작성 — 핵심 로직
src/MainActivity.kt에 아래 코드를 추가합니다. 이 코드가 스와이프 감지의 핵심입니다.
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()
}
}
}핵심 로직 설명
- GestureDetector: 터치 이벤트를 분석해 플링(빠른 스와이프) 동작을 감지합니다.
- onFling(): 스와이프 시작 지점(e1)과 끝 지점(e2)의 좌표 차이(diffX, diffY)를 계산합니다.
- 방향 판별: X축 이동량이 Y축보다 크면 좌우 스와이프, 그렇지 않으면 상하 스와이프로 판단합니다.
- 임계값(Threshold): 이동 거리 100px, 속도 100px/s 이상일 때만 유효한 스와이프로 인식해 오작동을 방지합니다.
- OnSwipeListener 인터페이스: 각 방향별 콜백 메서드를 제공하므로, 필요한 곳에서 스와이프 이벤트를 자유롭게 처리할 수 있습니다.
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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run ▶ 버튼을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면 기기에 앱이 실행됩니다.
화면에서 스와이프를 수행하면 방향에 따라 다음과 같이 토스트 메시지가 표시됩니다.


마무리
이렇게 GestureDetector와 OnTouchListener를 조합하면 좌/우/상/하 네 방향의 스와이프 이벤트를 정확하게 감지할 수 있습니다. 임계값을 조절하면 민감도를 튜닝할 수 있고, OnSwipeListener 인터페이스를 활용하면 이미지 슬라이더, 페이지 전환 등 다양한 UI 시나리오에 응용할 수 있습니다.