Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีทำ Long Click Listener บน ListView ใน Android ด้วย Kotlin

บทนำ

ตัวอย่างนี้สาธิตการเพิ่ม Listener สำหรับการคลิกค้าง (Long Click) บน ListView ใน Android โดยใช้ Kotlin

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

สร้างโปรเจกต์ใหม่ใน Android Studio

ขั้นตอนที่ 2: Layout (activity_main.xml)

เพิ่มโค้ดใน 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>

ขั้นตอนที่ 3: MainActivity.kt

เพิ่มโค้ดใน 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(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 // คืนค่า true เพื่อบ่งชี้ว่าได้จัดการเหตุการณ์แล้ว
        }
    }
}

ขั้นตอนที่ 4: AndroidManifest.xml

ตรวจสอบการประกาศ Activity หลัก

การทดสอบ

รันแอปบนอุปกรณ์จริง คลิกค้างที่รายการใดๆ ใน ListView จะแสดง Toast "Long clicked"

วิธีทำ Long Click Listener บน ListView ใน Android ด้วย Kotlin

หมายเหตุ: ปัจจุบันแนะนำให้ใช้ RecyclerView แทน ListView เนื่องจากมีประสิทธิภาพดีกว่าและรองรับฟีเจอร์มากกว่า