編輯:Android 資訊
RecyclerView 是傳統 ListView 的優秀替代者,擴展性極強。初次接觸時,其相對複雜的邏輯可能會讓人暈頭轉向,本文就通過一個簡單實例,帶大家理清其中的關係。
本文使用的 IDE 為 Android Studio。依次點擊 File → Project Structure → 左下角 Module 的 app → Dependencies → 點擊左下方的「+」,選擇 recycler view 即可。
首先創建一個名為 NotesListFragment 的 Fragment,對應布局文件名為 fragment_notes_list,接著將它加入主 Activity(如何在 Activity 中操作 Fragment 將另文說明,此處從略)。然後在 NotesListFragment 中定義一個私有字段:
private RecyclerView noteRecycler;
我們要實現的是一個展示筆記的 RecyclerView,這裡將筆記類 Note 定義如下:
package com.aristark.note; import java.util.Date; import java.util.UUID; public class Note { private UUID uuid; private String title; private String content; private Date date; private String tag; public Note{ uuid = UUID.randomUUID(); date = new Date(); } public UUID getUuid() { return uuid; } public Date getDate() { return date; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } public void setContent(String content) { this.content = content; } public String getContent() { return content; } public void setTag(String tag) { this.tag = tag; } public String getTag() { return tag; } }
為方便操作,我們再創建一個 NoteLab 類:
package com.aristark.note; import android.content.Context; import java.util.ArrayList; public class NoteLab { private static NoteLab sNoteLab; //for the global use private ArrayList<Note> notes; private NoteLab(Context context){ notes = new ArrayList<Note>(); //generate 100 Note Objects for (int i=0;i<100;i++){ Note note = new Note(); note.setTitle("this is title "+i); note.setContent("this is content"+i+"balabala..."); notes.add(note); } } public static NoteLab getNoteLab(Context context){ if (sNoteLab == null){ sNoteLab = new NoteLab(context); } return sNoteLab; } public ArrayList<Note> getNotes() { return notes; } }
注意體會該類使用的單例模式:sNoteLab 以靜態方式存在,既節省內存,又方便各部件訪問。構造方法 NoteLab 中我們生成了 100 個 Note 對象用於後續測試。
這兩個類是實現列表的關鍵。從字面不難猜測:ViewHolder 負責每個列表項的布局,Adapter 則用數據填充 View。下面我們就在 NotesListFragment 裡創建這兩個類。
1. 首先創建 NoteHolder:
private class NoteHolder extends RecyclerView.ViewHolder{ public NoteHolder(View root) { super(root); } }
這個類很簡單。值得注意的是,自動生成的構造方法參數名為 itemView,這裡我改成 root,因為接下來傳進來的是一個完整的布局文件,而不僅僅是一個控件。
2. 創建 Adapter:
private class NoteAdapter extends RecyclerView.Adapter<NoteHolder>{ private List<Note> notes; public NoteAdapter(List<Note> notes){ this.notes = notes; } @Override public NoteHolder onCreateViewHolder(ViewGroup parent, int viewType) { return null; } @Override public void onBindViewHolder(NoteHolder holder, int position) { } @Override public int getItemCount() { return 0; } }
前面說 Adapter 負責數據操作,因此內部定義 notes 字段很好理解。再看這三個復寫的方法:onCreateViewHolder 返回 NoteHolder,用於創建 ViewHolder;onBindViewHolder 可直接操作 NoteHolder,position 指當前 View 在整個列表中的位置,以便按位置填入相應數據;getItemCount 則返回所需布局的總數。
talk is cheap, show me the code。下面看完整代碼,多看幾遍自然會用:
private class NoteAdapter extends RecyclerView.Adapter<NoteHolder>{ private List<Note> notes; public NoteAdapter(List<Note> notes){ this.notes = notes; } public void setNotes(List<Note> notes) { this.notes = notes; } @Override public NoteHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(getActivity()); View view = layoutInflater.inflate(R.layout.list_item_note,parent,false); return new NoteHolder(view); } @Override public void onBindViewHolder(NoteHolder holder, int position) { Note note = notes.get(position); holder.bindView(note); } @Override public int getItemCount() { return notes.size(); } }
其中 R.layout.list_item_note 的布局文件如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/list_item_note_title" /> </LinearLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/list_item_note_content" /> </LinearLayout>
這裡只簡單用了 Note 的 title 和 content 兩個字段。其實這個 view 就是整個列表的模板,只是依次填充不同數據而已。
准備好 ViewHolder 和 Adapter 後,接下來就是把它們組裝起來。最後貼出完整的 Fragment,請注意 onCreateView 裡的操作!
public class NotesListFragment extends Fragment { private RecyclerView noteRecycler; private NoteAdapter noteAdapter; public NotesListFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_notes_list,container,false); noteRecycler = (RecyclerView) root.findViewById(R.id.note_recycler_view); noteRecycler.setLayoutManager(new LinearLayoutManager(getActivity())); NoteLab noteLab = NoteLab.getNoteLab(getActivity()); ArrayList<Note> notes = noteLab.getNotes(); noteAdapter = new NoteAdapter(notes); noteRecycler.setAdapter(noteAdapter); return root; } private class NoteHolder extends RecyclerView.ViewHolder{ private TextView noteTitle; private TextView noteContent; public NoteHolder(View root) { super(root); noteTitle = (TextView) root.findViewById(R.id.list_item_note_title); noteContent = (TextView) root.findViewById(R.id.list_item_note_content); } public void bindView(Note note){ noteTitle.setText(note.getTitle()); noteContent.setText(note.getContent()); } } private class NoteAdapter extends RecyclerView.Adapter<NoteHolder>{ private List<Note> notes; public NoteAdapter(List<Note> notes){ this.notes = notes; } @Override public NoteHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(getActivity()); View view = layoutInflater.inflate(R.layout.list_item_note,parent,false); return new NoteHolder(view); } @Override public void onBindViewHolder(NoteHolder holder, int position) { Note note = notes.get(position); holder.bindView(note); } @Override public int getItemCount() { return notes.size(); } } }
最後貼出運行效果圖。
這是我第一次寫博客,解釋不多、代碼較多:一来缺乏表達經驗,二来我始終覺得很多時候類名、函數名本身就足以說明用途,過多解釋反而怕誤導大家。無論如何,希望能得到大家的支持。我會在堅持寫代碼的同時把博客寫下去,既是對所學知識的總結,也希望確實能幫到需要的朋友。有任何技術交流問題都歡迎聯繫我,批評也一樣歡迎!
正確使用 Android 性能分析工具 TraceView
前面唠叨 最近公司 app 中有些列表在滑動時會有卡頓現象,我便著手解決這些問題。解決問題之前,首先要分析列表滑動的性能瓶頸在哪裡。因為之前不會正確使用 TraceVie
用 Android Support Annotations 替程式碼加上安全網
Support Annotations 是一組以 Java 註解表達的輕量約束,能幫助 Android Studio 在編寫階段發現潛在錯誤。它不改變應用邏輯,卻能讓空值
Android 經典側滑菜單 SlidingMenu 使用指南
本文由碼農網 – 小峰原創,轉載請看清文末的轉載要求,歡迎參與我們的付費投稿計劃! SlidingMenu 是一款開源的 Android 類庫,能讓開發者在自己的 App
Android UI 控件系列:Button 按鈕
Button 就是按鈕,是 Android 中應用最多的組件之一。它有兩種用法:一是在 XML 中配置,二是直接在程序中操作。 在 XML 布局中,常會遇到這些單位: p