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

วิธีจัดการเหตุการณ์คลิกใน ListView ใน Android ด้วย Kotlin

ภาพรวม

ตัวอย่างนี้สาธิตวิธีการจัดการเหตุการณ์คลิก (Click Event) ใน ListView ใน Android โดยใช้ setOnItemClickListener และ Kotlin

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

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

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอหลัก (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text="Choose is the best football player?"
        android:textColor="@android:color/holo_purple"
        android:textStyle="italic|bold" />
    <ListView
        android:id="@+id/listView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textView" />
</RelativeLayout>

ขั้นตอนที่ 3: เขียนโค้ด MainActivity.kt

import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlin.collections.ArrayList

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        val listView: ListView = findViewById(R.id.listView)
        val textView: TextView = findViewById(R.id.textView)

        val players = arrayOf("Cristiano Ronaldo", "Messi", "Pele", "Ronaldinho", "Maradona", "Neymar")
        val playerList = ArrayList(listOf(*players))
        val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, playerList)
        listView.adapter = arrayAdapter

        listView.setOnItemClickListener { parent, _, position, _ ->
            val selectedItem = parent.getItemAtPosition(position) as String
            textView.text = "The best football player is $selectedItem"
        }
    }
}

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

ใช้การตั้งค่ามาตรฐาน

ทดสอบการทำงาน

รันแอป คลิกที่รายการใน ListView ข้อความด้านบนจะเปลี่ยนแสดงนักฟุตบอลที่เลือก

ข้อมูลเพิ่มเติม

  • RecyclerView: แทนที่ ListView ในแอปทันสมัย ใช้ RecyclerView + Adapter + ViewHolder รองรับ ClickListener ได้ยืดหยุ่นกว่า
  • Long Click: ใช้ setOnItemLongClickListener สำหรับการกดค้าง
  • Context Menu: ใช้ registerForContextMenu(listView) และ override onCreateContextMenu