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

วิธีเปลี่ยนสีพื้นหลัง ListView Items เมื่อคลิกใน Android ด้วย Kotlin

ตัวอย่างนี้สาธิตวิธี เปลี่ยนสีพื้นหลัง Item ใน ListView เมื่อผู้ใช้คลิก โดยใช้ setOnItemClickListener และ setBackgroundColor

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

Android Studio → New Project → Empty Activity

ขั้นตอนที่ 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

ขั้นตอนที่ 3: ใส่สีใน res/values/colors.xml

<resources>
    <color name="colorAccent">#FF4081</color>
    <color name="selected_item">#E0E0E0</color>
</resources>

ขั้นตอนที่ 4: โค้ดหลัก (MainActivity.kt)

import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {
    private val operatingSystems = arrayOf(
        "Android", "iPhone", "Windows Mobile", "BlackBerry",
        "WebOS", "Ubuntu", "Windows 7", "macOS"
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "ListView Item Color Demo"

        val listView = findViewById(R.id.listView)
        val adapter = ArrayAdapter(
            this, android.R.layout.simple_list_item_1, operatingSystems
        )
        listView.adapter = adapter

        listView.setOnItemClickListener { _, view, position, _ ->
            // 🔑 เปลี่ยนสีพื้นหลัง View ที่ถูกคลิก
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                view.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent))
            } else {
                // Deprecated แต่ยังทำงานได้
                view.setBackgroundColor(resources.getColor(R.color.colorAccent))
            }

            // แสดงข้อความยืนยัน
            Toast.makeText(this, "Selected: ${operatingSystems[position]}", Toast.LENGTH_SHORT).show()
        }
    }
}

🎨 วิธีขั้นสูง: ใช้ Selector (State List Drawable)

สร้าง res/drawable/list_item_selector.xml แล้วตั้งให้ ListView:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/colorAccent" />
    <item android:state_selected="true" android:drawable="@color/selected_item" />
    <item android:drawable="@android:color/transparent" />
</selector>

ใช้ใน Adapter: view.setBackgroundResource(R.drawable.list_item_selector)

💡 แนวทางทันสมัย: RecyclerView

ปัจจุบันแนะนำ RecyclerView ซึ่ง:

  • มี ViewHolder บังคับใช้ → ประสิทธิภาพดีกว่า
  • รองรับ ItemTouchHelper, Animation
  • ควบคุม State (Pressed, Selected, Focused) ได้ละเอียดกว่า

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

Manifest มาตรฐาน

ทดสอบ

  1. รันแอป → แสดงรายการ OS 8 รายการ
  2. กด Item ใด Item หนึ่ง → พื้นหลังสีชมพู (colorAccent)
  3. Scroll ลง-ขึ้น → Item ที่คลิกเก็บสีไว้ (เพราะ View ถูก Recycle อาจหาย)

⚠️ หมายเหตุ

ListView ใช้ View Recycling → สีอาจหายเมื่อ Scroll หากต้องการ Persistent Selection ต้องเก็บ State ใน Adapter เอง หรือเปลี่ยนมาใช้ RecyclerView