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

Cách tạo ListView ngang (Horizontal RecyclerView) trong Android

Hướng dẫn này minh họa cách tạo danh sách cuộn ngang (horizontal list) bằng RecyclerView với LinearLayoutManager.HORIZONTAL — cách hiện đại thay thế HorizontalListView cũ.

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

Mở Android Studio, chọn File → New Project.

Bước 2: Giao diện chính (res/layout/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="wrap_content" />

</LinearLayout>

Bước 3: Item layout (res/layout/movie_list.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="250dp"
    android:layout_height="120dp"
    android:layout_margin="8dp"
    app:cardCornerRadius="8dp"
    app:cardElevation="4dp">

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

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_toStartOf="@+id/year"
            android:textColor="#222222"
            android:textSize="16sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/year"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:textColor="#999999" />

        <TextView
            android:id="@+id/genre"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:textColor="#666666"
            android:textSize="14sp" />

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

Bước 4: Model (src/MovieModel.java)

package app.com.sample;

public class MovieModel {
    private String title, genre, year;

    public MovieModel() {}
    public MovieModel(String title, String genre, String year) {
        this.title = title; this.genre = genre; this.year = year;
    }
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
    public String getGenre() { return genre; }
    public void setGenre(String genre) { this.genre = genre; }
    public String getYear() { return year; }
    public void setYear(String year) { this.year = year; }
}

Bước 5: Adapter (src/MoviesAdapter.java)

package app.com.sample;

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;
import java.util.List;

public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {
    private final List<MovieModel> moviesList;

    public MoviesAdapter(List<MovieModel> moviesList) {
        this.moviesList = moviesList;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        MovieModel movie = moviesList.get(position);
        holder.title.setText(movie.getTitle());
        holder.genre.setText(movie.getGenre());
        holder.year.setText(movie.getYear());
    }

    @Override
    public int getItemCount() {
        return moviesList.size();
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {
        TextView title, genre, year;
        MyViewHolder(View view) {
            super(view);
            title = view.findViewById(R.id.title);
            genre = view.findViewById(R.id.genre);
            year = view.findViewById(R.id.year);
        }
    }
}

Bước 6: MainActivity (src/MainActivity.java)

package app.com.sample;

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;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private final List<MovieModel> movieList = new ArrayList<>();
    private MoviesAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        adapter = new MoviesAdapter(movieList);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); // QUAN TRỌNG: ngang
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);

        prepareMovieData();
    }

    private void prepareMovieData() {
        String[][] data = {
            {"Mad Max: Fury Road", "Action & Adventure", "2015"},
            {"Inside Out", "Animation, Kids & Family", "2015"},
            {"Star Wars: Episode VII", "Action", "2015"},
            {"Shaun the Sheep", "Animation", "2015"},
            {"The Martian", "Sci-Fi & Fantasy", "2015"},
            {"Mission: Impossible Rogue Nation", "Action", "2015"},
            {"Up", "Animation", "2009"},
            {"Star Trek", "Sci-Fi", "2009"},
            {"The LEGO Movie", "Animation", "2014"},
            {"Iron Man", "Action & Adventure", "2008"},
            {"Aliens", "Sci-Fi", "1986"},
            {"Chicken Run", "Animation", "2000"},
            {"Back to the Future", "Sci-Fi", "1985"},
            {"Raiders of the Lost Ark", "Action & Adventure", "1981"},
            {"Goldfinger", "Action & Adventure", "1965"},
            {"Guardians of the Galaxy", "Sci-Fi & Fantasy", "2014"}
        };

        for (String[] d : data) {
            movieList.add(new MovieModel(d[0], d[1], d[2]));
        }
        adapter.notifyDataSetChanged();
    }
}

Bước 7: Manifest (androidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <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>

💡 Mẹo: Snap to center (căn giữa item khi cuộn dừng)

// Thêm dependency: implementation 'androidx.recyclerview:recyclerview:1.2.0+'
LinearLayoutManager lm = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(lm);
SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Danh sách phim cuộn ngang mượt mà, mỗi item là một CardView.