Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách xử lý sự kiện click Item trong ListView Android bằng Kotlin

Giới thiệu

Ví dụ minh họa cách bắt sự kiện click vào từng item của ListView và hiển thị item được chọn lên TextView bằng Kotlin.

Các bước thực hiện

Bước 1: Tạo dự án mới

Android Studio > File > New Project.

Bước 2: Layout (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="Chọn cầu thủ bóng đá tốt nhất?"
        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>

Bước 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(players.asList())

        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 = "Cầu thủ tốt nhất là $selectedItem"
        }
    }
}

Bước 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.listviewclick">

    <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>

Chạy ứng dụng

Chạy app, danh sách cầu thủ hiện ra. Click vào tên bất kỳ, TextView trên cùng cập nhật: "Cầu thủ tốt nhất là [Tên]".

Mở rộng: Custom Adapter & ViewHolder

Để hiển thị layout phức tạp (ảnh, nhiều text), cần tạo Custom Adapter:

// 1. Layout item: res/layout/item_player.xml (ImageView + TextView)
// 2. Model: data class Player(val name: String, val imageRes: Int)
// 3. Adapter:
class PlayerAdapter(private val context: Context, private val list: List) :
    BaseAdapter() {
    override fun getCount() = list.size
    override fun getItem(position: Int) = list[position]
    override fun getItemId(position: Int) = position.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view = convertView ?: LayoutInflater.from(context).inflate(R.layout.item_player, parent, false)
        val holder = view.tag as? ViewHolder ?: ViewHolder(view).also { view.tag = it }
        holder.bind(list[position])
        return view
    }

    class ViewHolder(view: View) {
        val nameTv: TextView = view.findViewById(R.id.tvName)
        val imgIv: ImageView = view.findViewById(R.id.ivImage)
        fun bind(player: Player) {
            nameTv.text = player.name
            imgIv.setImageResource(player.imageRes)
        }
    }
}

// 4. Set adapter & click listener
listView.adapter = PlayerAdapter(this, players)
listView.setOnItemClickListener { _, _, pos, _ ->
    val player = players[pos]
    Toast.makeText(this, "Đã chọn ${player.name}", Toast.LENGTH_SHORT).show()
}

Lưu ý: ListView vs RecyclerView

  • ListView: Cũ, đơn giản, ít tính năng, không bắt buộc ViewHolder (nhưng nên dùng).
  • RecyclerView: Mới, mạnh mẽ, bắt buộc ViewHolder, hỗ trợ LayoutManager (Grid, Staggered), ItemAnimator, ItemDecoration, DiffUtil. Khuyến nghị dùng RecyclerView cho project mới.