iT邦幫忙

2024 iThome 鐵人賽

DAY 20
0

RecyclerView是個在需要顯示大量資料時非常好用的元件
它在顯示資料時若是數量太多不會變形會被截掉,只要往下滑動就可以顯示出未顯示的資料了
下面直接來帶一個簡單的小例題

首先,要先開一個新的Activity
這邊將新的Activity命名為recyclerview_item
這個新的Activity是用來設定每一筆資料的顯示格式的
https://ithelp.ithome.com.tw/upload/images/20240928/20168456j7od8ehCvz.png
這邊將它拉成這樣,後面程式執行後每一筆資料都會以這種格式去顯示,只要依照自己想要的方式去拉就好了
但是有一點要特別注意
https://ithelp.ithome.com.tw/upload/images/20240928/201684569B47KtBllN.png
紅色框框的的那兩個地方一定要記得改設定
不然它的上面那邊預設會是match_parent,但若是設定成這樣的話,它會變成一筆資料就一頁除了那筆資料以外的地方都會是空白
像這樣
https://ithelp.ithome.com.tw/upload/images/20240928/20168456gsxZ2tGk32.png
往下滑後雖然可以顯示下一筆資料但顯示會很奇怪
https://ithelp.ithome.com.tw/upload/images/20240928/20168456Dj1JQwYEf5.png
更改後才會正常顯示

接著進到activity_main
這邊我是這樣拉,但其他上面那條可有可無看個人決定要不要留下來吧
https://ithelp.ithome.com.tw/upload/images/20240928/20168456HjUCjDtJkA.png
下面那個就是RecyclerView元件了

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/main_recyclerview_rv"
        android:layout_width="0dp"
        android:layout_height="0dp"/>

這個一定要記得拉不然資料不會顯示

接著來到MainActivity
首先是假資料的部分

private RecyclerView showRecyclerView;
private ListAdapter listAdapter;
final static String[] store = {"abc", "123", "48763", "hello world", "apple"};

先定義一些基本的東西

ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();

新增一個HashMap存放每筆資料

for (int i = 0; i < 20; i++) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("number",String.format("%02d", i + 1));
        hashMap.put("store",String.valueOf(store[new Random().nextInt(5)]));
        hashMap.put("point", "+" + new Random().nextInt(1000));
        arrayList.add(hashMap);
    }

利用迴圈呼叫20次將20筆不同資料放入HashMap

showRecyclerView = findViewById(R.id.main_recyclerview_rv);

綁定元件

showRecyclerView.setLayoutManager(new LinearLayoutManager(this));
showRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
listAdapter = new ListAdapter();
showRecyclerView.setAdapter(listAdapter);

設置recyclerveiw

private class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder> {

        class ViewHolder extends RecyclerView.ViewHolder {
            private TextView numberTv, storeTv, pointTv;
            public ViewHolder(View itemView) {
                super(itemView);
                numberTv = itemView.findViewById(R.id.recycleview_number_tv);
                storeTv = itemView.findViewById(R.id.recycleview_store_tv);
                pointTv = itemView.findViewById(R.id.recycleview_point_tv);
            }
        }
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.recycleview_item, parent, false);
            return new ViewHolder(view);
        }
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            holder.numberTv.setText(arrayList.get(position).get("number"));
            holder.storeTv.setText(arrayList.get(position).get("store"));
            holder.pointTv.setText(arrayList.get(position).get("point"));
        } //從HashMap中抓取資料並將其印出
        @Override
        public int getItemCount() {
            return arrayList.size();
        }
        //回傳arrayList的大小
    }

接著在加入ListAdapter就可以正常使用了

  • 這是執行後的樣子
    https://ithelp.ithome.com.tw/upload/images/20240928/20168456Qnbir4WSM4.png
    https://ithelp.ithome.com.tw/upload/images/20240928/20168456PHl7aZm6zO.png

下面是完整的程式碼

xml

activity_main

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

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal"
        android:background="#A88CD0"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/textView"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.3"
            android:gravity="center"
            android:text="順序"
            android:textSize="20dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/textView4"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:textSize="20dp"
            android:textStyle="bold"
            android:text="店家" />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.3"
            android:gravity="center"
            android:textSize="20dp"
            android:textStyle="bold"
            android:text="點數" />
    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/main_recyclerview_rv"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout" />
</androidx.constraintlayout.widget.ConstraintLayout>

recyclerview_item

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="50dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/recycleview_number_tv"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center"
            android:layout_weight="0.3"
            android:text="TextView" />

        <TextView
            android:id="@+id/recycleview_store_tv"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="TextView" />

        <TextView
            android:id="@+id/recycleview_point_tv"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center"
            android:layout_weight="0.3"
            android:text="TextView" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity

package com.example.test_2;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

public class MainActivity extends AppCompatActivity {
    private RecyclerView showRecyclerView;
    private ListAdapter listAdapter;
    final static String[] store = {"abc", "123", "48763", "hello world", "apple"};
    ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();

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

        for (int i = 0; i < 20; i++) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("number",String.format("%02d", i + 1));
            hashMap.put("store",String.valueOf(store[new Random().nextInt(5)]));
            hashMap.put("point", "+" + new Random().nextInt(1000));

            arrayList.add(hashMap);
        }//利用迴圈呼叫20次將20筆不同資料放入HashMap中
        showRecyclerView = findViewById(R.id.main_recyclerview_rv); //綁定元件

        showRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        showRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        listAdapter = new ListAdapter();
        showRecyclerView.setAdapter(listAdapter);
    }
    private class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder> {

        class ViewHolder extends RecyclerView.ViewHolder {
            private TextView numberTv, storeTv, pointTv;
            public ViewHolder(View itemView) {
                super(itemView);
                numberTv = itemView.findViewById(R.id.recycleview_number_tv);
                storeTv = itemView.findViewById(R.id.recycleview_store_tv);
                pointTv = itemView.findViewById(R.id.recycleview_point_tv);
            }
        }
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.recycleview_item, parent, false);
            return new ViewHolder(view);
        }
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            holder.numberTv.setText(arrayList.get(position).get("number"));
            holder.storeTv.setText(arrayList.get(position).get("store"));
            holder.pointTv.setText(arrayList.get(position).get("point"));
        }
        @Override
        public int getItemCount() {
            return arrayList.size();
        }
    }

}

這樣就完成RecyclerView的假資料了
下篇會介紹RecyclerView的點擊事件與下滑更新


上一篇
[Day 19] Dialog介紹
下一篇
[Day 21] RecyclerView的點擊事件與下滑更新
系列文
深入Android Java程式語言 - 打造我的行動應用30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言