Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Kotlin으로 Android ListView 롱 클릭(Long Click) 리스너 구현하는 방법

이 튜토리얼에서는 Kotlin을 사용하여 Android의 ListView(리스트 뷰)에서 항목을 길게 눌렀을 때 동작하는 롱 클릭(Long Click) 리스너를 구현하는 방법을 단계별로 살펴봅니다.

1단계: 새 프로젝트 만들기

Android Studio를 실행하고 File ⇒ New Project 메뉴로 이동한 후, 새 프로젝트 생성에 필요한 모든 정보를 입력하여 새 프로젝트를 만듭니다.

2단계: 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

위 레이아웃은 화면 전체를 차지하는 하나의 ListView를 포함하는 간단한 세로 방향 LinearLayout 구조입니다.

3단계: MainActivity에 롱 클릭 리스너 구현

src/MainActivity.kt 파일에 아래 코드를 추가합니다.

import android.os.Bundle
import android.widget.AdapterView.OnItemLongClickListener
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
    var mobileArray = arrayOf("Android", "IPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        val listView: ListView = findViewById(R.id.listView)
        val adapter: ArrayAdapter<*> = ArrayAdapter<Any?>(this, android.R.layout.simple_list_item_1, mobileArray)
        listView.adapter = adapter
        listView.onItemLongClickListener = OnItemLongClickListener { _, _, _, _ ->
            Toast.makeText(applicationContext, "Long clicked", Toast.LENGTH_SHORT).show()
            true
        }
    }
}

핵심 부분은 onItemLongClickListener입니다. 리스트 항목을 길게 누르면 OnItemLongClickListener가 호출되어 화면에 "Long clicked"라는 토스트 메시지를 표시합니다. 콜백 마지막의 true 반환 값은 이 이벤트를 소비(consume)했음을 의미하며, 이렇게 해야 일반 클릭 이벤트가 함께 발생하지 않습니다.

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 아이콘을 클릭하세요. 실행 옵션 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 앱의 기본 화면이 표시됩니다.

앱이 실행되면 리스트에서 임의의 항목을 길게 눌러 보세요. 화면 하단에 "Long clicked" 토스트 메시지가 나타나는 것을 확인할 수 있습니다.