iT邦幫忙

2024 iThome 鐵人賽

DAY 19
0

RecyclerView 可捲動的清單,這次我們來教如何使用recyclerView將假資料做成現,也配合之前交的MVP架構做使用。


RecyclerView

  • 這次我們需要新增2個class和一個interface,對著自己的com.example 右鍵>New>Java Class ,進行新增命名
    (Model在這單元不需要所以沒有新增,新增也沒關係,之後若有需要使用少一個動作)
    https://ithelp.ithome.com.tw/upload/images/20240927/20168454XOjWOFvOaQ.png

  • 還要新增一個在layout的.xml,在layoutu右鍵>New>Layout Resource File,進行新增命名
    https://ithelp.ithome.com.tw/upload/images/20240927/20168454dZxr5YY0h5.png

  • 完成新增畫面
    https://ithelp.ithome.com.tw/upload/images/20240927/2016845465shA4Hnrs.png

  • 於Palette 拖移一個recyclerView
    https://ithelp.ithome.com.tw/upload/images/20240927/20168454SAeeZSmTQU.png

  • 將其占全版面 (.xml 介面)
    https://ithelp.ithome.com.tw/upload/images/20240927/20168454GrJv1dXY7O.png

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

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/main_list_rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
  • 設計recyclerView樣子(.xml),這裡使用了LinearLayout進行排版(LinearLayout之後也會介紹)
    https://ithelp.ithome.com.tw/upload/images/20240927/20168454jwEsUZ76ay.png
<?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:layout_width="match_parent"
    android:layout_height="50dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

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

            <TextView
                android:id="@+id/main_recnumber_tv"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center"
                android:text="TextView"
                android:textColor="@color/black"
                android:textSize="20dp" />

            <TextView
                android:id="@+id/main_recdata_tw"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:text="TextView"
                android:textColor="@color/black"
                android:textSize="20dp" />
        </LinearLayout>

    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity
public class MainActivity extends AppCompatActivity implements MainContract.view{

    //設定RecycleView類別的變數名稱recycleView
    private RecyclerView recyclerView;
    MainAdapter mainAdapter;
    private MainPresenter mainPresenter;

    //新增一個HashMap存放每筆資料
    ArrayList<HashMap<String, String>> marrayList = new ArrayList<>();

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

        mainPresenter = new MainPresenter(this);
        mainPresenter.Data();

        //設置RecycleView
        recyclerView = findViewById(R.id.main_list_rv);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mainAdapter = new MainAdapter(marrayList);
        recyclerView.setAdapter(mainAdapter);
    }

    @Override
    public void getData(ArrayList arrayList) {
        marrayList = arrayList;
    }
}
MainPresenter
  • 產生我們需要的假資料
public class MainPresenter implements MainContract.mainPresenter{
    private MainContract.view callback;

    ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();
    final static String[] name = {"小丸子", "花媽", "Ben10", "海綿寶寶", "阿天"};

    public MainPresenter(MainContract.view view){
        this.callback = view;
    }

    @Override
    public void Data(){
        //利用迴圈呼叫20次將20筆不同資料放入HashMap中
        for (int i = 0; i < 20; i++) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("number",String.format("%02d", i + 1));
            hashMap.put("data","name : "+String.valueOf(name[new Random().nextInt(5)]));

            arrayList.add(hashMap);
        }

        callback.getData(arrayList);
    }
}

MainAdapter
  • 第一步,打完下方圖片這一行
    https://ithelp.ithome.com.tw/upload/images/20240927/20168454z9W2O7GUFc.png

  • 之後使用快捷鍵Alt + Enter ,選擇Implement methods
    https://ithelp.ithome.com.tw/upload/images/20240927/20168454Ohlbrn8n3n.png

  • 點選OK
    https://ithelp.ithome.com.tw/upload/images/20240927/20168454laosYvJ8jD.png

  • 再一次使用快捷鍵Alt + Enter
    https://ithelp.ithome.com.tw/upload/images/20240927/20168454dfOcXD8DFu.png

  • 選擇 第一個
    https://ithelp.ithome.com.tw/upload/images/20240927/20168454vHHonGzHIi.png

  • 紅色底線使用快捷鍵Alt + Enter,選擇第一個
    https://ithelp.ithome.com.tw/upload/images/20240927/20168454jwGzakY2QN.png

  • 最後一次使用快捷鍵Alt + Enter,選擇第一個
    https://ithelp.ithome.com.tw/upload/images/20240927/20168454ZmPtVHe4Nq.png

  • 這樣就完成了
    https://ithelp.ithome.com.tw/upload/images/20240927/201684548WhCJtEntt.png

  • 完成程式碼
    記得layout要綁正確喔

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
    ArrayList<HashMap<String,String>> arrayList = new ArrayList<>();

    class ViewHolder extends RecyclerView.ViewHolder {
        private TextView tx1,tx2;

        public ViewHolder(View itemView) {
            super(itemView);
            tx1 = itemView.findViewById(R.id.main_recnumber_tv);
            tx2 = itemView.findViewById(R.id.main_recdata_tw);
        }
    }

    public MainAdapter(ArrayList<HashMap<String,String>> arrayList){
        this.arrayList = arrayList;
    }

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

    //從HashMap中抓取資料並將其印出
    @Override
    public void onBindViewHolder(MainAdapter.ViewHolder holder, int position) {
        holder.tx1.setText(arrayList.get(position).get("number"));
        holder.tx2.setText(arrayList.get(position).get("data"));

    }

    //回傳arrayList的大小
    @Override
    public int getItemCount() {
        return arrayList.size();
    }
}

MainContract
package com.example.reclist;

import java.util.ArrayList;

public interface MainContract {
    interface view {
        void getData(ArrayList arrayList);
    }

    interface mainPresenter {
        void Data();
    }
}

執行畫面

跟著上面做完,我們就成功獲得一個最簡單使用RecyclerView做出的可捲動的清單啦~

執行大概是這樣,按住可上下滑動。
我們是將左邊的TextView放數字排序,右邊的TextView放隨機名字。

(剛開始)
https://ithelp.ithome.com.tw/upload/images/20240927/20168454gPS5VmuDhT.png

(下滑)
https://ithelp.ithome.com.tw/upload/images/20240927/20168454UFsxChU6Fw.png


上一篇
元件篇-Dialog(下) Day18
下一篇
元件篇-RecyclerView下滑更新 Day20
系列文
Android 元件總動員 - 運用與實踐元件指南30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言