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

วิธีสร้าง Horizontal ListView ใน Android ด้วย Kotlin

ภาพรวม

ตัวอย่างนี้สาธิตวิธาสร้างรายการแนวนอน (Horizontal ListView) ใน Android โดยใช้ RecyclerView และ Kotlin ซึ่งเป็นวิธีที่ทันสมัยและมีประสิทธิภาพมากกว่า ListView แบบเดิม

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

เปิด Android Studio เลือก File → New Project กรอกรายละเอียดที่จำเป็น

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

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

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.util.ArrayList

class MainActivity : AppCompatActivity() {
    private val movieList = ArrayList<MovieModel>()
    private lateinit var moviesAdapter: MoviesAdapter

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

        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        moviesAdapter = MoviesAdapter(movieList)

        // ตั้งค่า LayoutManager แนวนอน
        val layoutManager = LinearLayoutManager(applicationContext)
        layoutManager.orientation = LinearLayoutManager.HORIZONTAL
        recyclerView.layoutManager = layoutManager

        recyclerView.itemAnimator = DefaultItemAnimator()
        recyclerView.adapter = moviesAdapter

        prepareMovieData()
    }

    private fun prepareMovieData() {
        val movies = listOf(
            MovieModel("Mad Max: Fury Road", "Action & Adventure", "2015"),
            MovieModel("Inside Out", "Animation, Kids & Family", "2015"),
            MovieModel("Star Wars: Episode VII - The Force Awakens", "Action", "2015"),
            MovieModel("Shaun the Sheep", "Animation", "2015"),
            MovieModel("The Martian", "Science Fiction & Fantasy", "2015"),
            MovieModel("Mission: Impossible Rogue Nation", "Action", "2015"),
            MovieModel("Up", "Animation", "2009"),
            MovieModel("Star Trek", "Science Fiction", "2009"),
            MovieModel("The LEGO Movie", "Animation", "2014"),
            MovieModel("Iron Man", "Action & Adventure", "2008"),
            MovieModel("Aliens", "Science Fiction", "1986"),
            MovieModel("Chicken Run", "Animation", "2000"),
            MovieModel("Back to the Future", "Science Fiction", "1985"),
            MovieModel("Raiders of the Lost Ark", "Action & Adventure", "1981"),
            MovieModel("Goldfinger", "Action & Adventure", "1965"),
            MovieModel("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014")
        )
        movieList.addAll(movies)
        moviesAdapter.notifyDataSetChanged()
    }
}

ขั้นตอนที่ 4: สร้างโมเดลข้อมูล (MovieModel.kt)

data class MovieModel(
    var title: String,
    var genre: String,
    var year: String
)

ขั้นตอนที่ 5: สร้าง Adapter (MoviesAdapter.kt)

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.NonNull
import androidx.recyclerview.widget.RecyclerView

class MoviesAdapter(private val moviesList: List<MovieModel>) :
    RecyclerView.Adapter<MoviesAdapter.MyViewHolder>() {

    inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val title: TextView = view.findViewById(R.id.title)
        val year: TextView = view.findViewById(R.id.year)
        val genre: TextView = view.findViewById(R.id.genre)
    }

    @NonNull
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val itemView = LayoutInflater.from(parent.context)
            .inflate(R.layout.movie_list, parent, false)
        return MyViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val movie = moviesList[position]
        holder.title.text = movie.title
        holder.genre.text = movie.genre
        holder.year.text = movie.year
    }

    override fun getItemCount(): Int = moviesList.size
}

ขั้นตอนที่ 6: สร้าง Layout รายการ (movie_list.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    app:cardBackgroundColor="@android:color/holo_red_dark"
    app:cardCornerRadius="8dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="8dp">

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:textSize="16sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/year"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/title"
            android:textColor="@android:color/white" />

        <TextView
            android:id="@+id/genre"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/year"
            android:textColor="@android:color/white" />

    </RelativeLayout>
</androidx.cardview.widget.CardView>

ขั้นตอนที่ 7: กำหนดค่า Manifest

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

การทดสอบและหมายเหตุ

รันแอปบนอุปกรณ์จริง จะเห็นรายการภาพยนตร์เลื่อนได้ในแนวนอน ใช้ CardView เพื่อให้ UI ดูสวยงามและทันสมัย