iT邦幫忙

2025 iThome 鐵人賽

DAY 14
0

Recyclerview

RecyclerView 是 Android 中用來顯示大量資料的元件,它可以高效地顯示清單(List)或網格(Grid)資料,比傳統的 ListView 更強大、更彈性

整體結構圖:
image

activity_main.xml

首先我們先拉取一個recyclerView元件進佈局裡

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

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

    </RelativeLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

recyclerview.xml

然後我們res/layout中建立一個叫recyclerview的xml檔,用來設定recyclerview中每一筆資料的顯示樣式,如果有多組資料你想分開展示也可以多拉幾個TextView,後續再在Adapter中設定顯示文字就好。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:orientation="horizontal"
    android:padding="8dp"
    android:background="#FFFFFF">

    <TextView
        android:id="@+id/fileTitle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical|start"
        android:text="TextView"
        android:textSize="16sp"/>
        
</LinearLayout>


MyAdapter

它算是一個橋樑,主要功能是連接資料和RecyclerView,不同於上面的recyclerview.xml,這是控制整個RecyclerView在MainActivity顯示的樣式

package com.example.recyclerview;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    ArrayList<String> ItemList;  // 用來儲存顯示資料的字串列表
    public MyAdapter(ArrayList<String> itemList) {
        this.ItemList = itemList;
    }

    @Override
    // 當 RecyclerView 需要新的 ViewHolder 時呼叫此方法
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // 利用 LayoutInflater將layout(recyclerview.xml)轉換為View
        // parent.getContext() 表示從父容器取得 Context(必要才能載入 layout)
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recyclerview, parent, false);    // 載入每一筆列表項目的 layout
        return new ViewHolder(view);  // 回傳 ViewHolder 實例,包裹這個 View
    }

    @Override
    // 當 RecyclerView 要把資料綁定到 ViewHolder 時呼叫此方法
    public void onBindViewHolder(ViewHolder holder, int position) {
        // 從資料列表中取得該位置的字串,設定給 ViewHolder 的 TextView
        holder.fileTitle.setText(ItemList.get(position));
        // RecyclerView 會依需求回收與重複利用 ViewHolder,故資料會隨位置更新
    }

    @Override
    // 回傳資料筆數,RecyclerView 用來決定要顯示多少項目
    public int getItemCount() {
        return ItemList.size();
    }

    // 自訂 ViewHolder 類別,繼承自 RecyclerView.ViewHolder
    class ViewHolder extends RecyclerView.ViewHolder {
        public TextView fileTitle;  // 用來顯示字串的 TextView

        // ViewHolder 建構子,傳入該筆 item 對應的 View
        public ViewHolder(View holder) {
            super(holder);
            // 透過 findViewById 找出該 View 中的 TextView,方便後續操作
            fileTitle = (TextView) holder.findViewById(R.id.fileTitle);
        }
    }
}


MainActivity

上述三頁都寫完後就可以回到MainActivity來組裝我們的recyclerview了,將資料交給recyclerview,然後顯示出來

package com.example.recyclerview;

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

public class MainActivity extends AppCompatActivity {
    MyAdapter adapter;// 宣告自訂的 Adapter
    RecyclerView projectRecyclerView;
    ArrayList<String> titleList = new ArrayList();// 資料來源,存放字串項目

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

        projectRecyclerView = findViewById(R.id.main_project_rv);

        //給titleList資料
        for(int i = 0;i<20;i++){
            titleList.add("項目"+i);
        }

        projectRecyclerView.setLayoutManager(new LinearLayoutManager(this));     //垂直向下排列
        projectRecyclerView.addItemDecoration(new DividerItemDecoration(this,    //分隔線
                DividerItemDecoration.VERTICAL));
        //將串列titlelist傳入MyAdapter,最後由recyclerView取用
        adapter = new MyAdapter(titleList);
        projectRecyclerView.setAdapter(adapter);
    }
}


執行成果展示:
螢幕擷取畫面 2025-07-23 120046


補充:

如果希望讓recyclerview的背景顏色紅白交錯,記得在 recyclerview.xml 裡設定 id="container" 給最外層 LinearLayout,如果不喜歡這些顏色也可以自己更改喔!

// 設定列的背景顏色紅白交錯
int bgColor = (position % 2 == 0) ? Color.parseColor("#F4A7B9") : Color.WHITE;
holder.container.setBackgroundColor(bgColor);

上一篇
Day 13.Intent 2
下一篇
Day 15.正規表達式(Regular Expressions)
系列文
Android 新手的 30 天進化論:從初學者到小專案開發者15
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言