Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

如何使用 RecyclerView

編輯:關於 Android 程式設計

1. 概述

這是一篇翻譯文章。作為一名 Android 工程師,這是我第一次翻譯國外網站的文章,難免會有一些遺漏和錯誤,歡迎指正。

RecyclerView 是一種全新的 ViewGroup,它與其他 ViewGroup 一樣,以 adapter 為基礎來提供視圖。它被視為 ListView 和 GridView 的接班人(這也是我翻譯這篇文章的原因)。這個類由 support-v7 提供支持,其最大優勢在於擁有更強的可擴展框架,尤其是支持水平與垂直等多種布局方式。當你的數據集會隨用戶操作或網絡事件而變化時,就應該使用 RecyclerView。

如果要使用 RecyclerView,你需要完成以下幾項工作:

· RecyclerView.Adapter——負責處理數據集並將其綁定到視圖
· LayoutManager——負責定位每一個 item
· ItemAnimator——為增刪 item 等通用操作提供動畫處理

此外,它為 ListView 的添加和刪除操作提供了動畫效果,而這與以往的實現方式截然不同。RecyclerView 還進一步強化了 ViewHolder 模式。

如今,使用 ViewHolder 已經是一項值得推薦的最佳實踐,並且在新的框架中被深度集成。

1.1 與 ListView 對比

與其父類 ListView 相比,RecyclerView 具備以下不同之處:

· 強制使用 ViewHolder:ListView 的 adapter 並不要求使用 ViewHolder 模式(盡管開發者通常會用到),而 RecyclerView 則被要求必須使用 ViewHolder。
· 可定制的 Item 布局:ListView 只能進行垂直的 Linear 布局,且無法由用戶定制;而 RecyclerView 借助 RecyclerView.LayoutManager,可以實現水平列表、網格乃至交錯網格等各種布局。
· 簡便的 item 動畫:ListView 並未提供 item 增減時的動畫能力;而 RecyclerView 擁有 RecyclerView.ItemAnimator 類來專門處理 item 動畫。
· 手動管理數據源:ListView 擁有 ArrayAdapter、CursorAdapter 等多種適配器用於處理數組和數據庫結果集;而 RecyclerView.Adapter 需要用戶自行實現來支持數據適配。
· 手動 Item 裝飾:ListView 擁有 android:divider 屬性可快速間隔各 item;而 RecyclerView 需要使用 RecyclerView.ItemDecoration 對象來實現更靈活的分隔修飾。
· 手動點擊檢測:ListView 擁有 AdapterView.OnItemClickListener 接口來綁定點擊事件;而 RecyclerView 只支持 RecyclerView.OnItemTouchListener,它管理分散的 touch 事件,但並未內置现成的點擊處理。

2. RecyclerView 的組成

2.1 LayoutManagers

一個 RecyclerView 需要擁有一個 LayoutManager 和一個 Adapter 才能完成實例化。LayoutManager 負責將 itemView 插入到 RecyclerView,並決定何時重用那些用戶已看不見的 itemView。
RecyclerView 提供了以下內建的 LayoutManager:
LinearLayoutManager——顯示垂直或水平滾動的 items
GridLayoutManager——以網格形式顯示 items
StaggeredGridLayoutManager——以交錯網格形式顯示 items
如果要創建自定義的 LayoutManager,可以繼承 RecyclerView.LayoutManager 類。

2.2 RecyclerView.Adapter

RecyclerView 包含一個全新的 adapter。它與你之前用過的 adapter 類似,但具備一些特殊特征,例如必須使用 ViewHolder。你需要重寫兩個核心方法:一個是 inflate 視圖並創建它的 ViewHolder,另一個是將數據綁定到視圖上。好消息是第一個方法只在我們真正需要創建新視圖時才會調用,無需判斷它是否已被回收。

2.3 ItemAnimator

RecyclerView.ItemAnimator 會為 ViewGroup 收到 adapter 變更通知(如增刪、移動)時產生動畫效果。DefaultItemAnimator 作為默認動畫,擁有非常好的表現。更多細節可參考後文的相關章節。

3. 使用 RecyclerView

使用一個 RecyclerView 有以下幾個關鍵步驟:

1. 在 gradle 構建文件中添加 RecyclerView 支持庫
2. 定義一個 model 類作為數據源
3. 在 Activity 中添加一個 RecyclerView 來顯示 items
4. 創建一個自定義的 row 布局 XML 文件來呈現單個 item
5. 創建 RecyclerView.Adapter 和 ViewHolder
6. 將 adapter 綁定到數據源以填充 RecyclerView

以下將對這些步驟逐一詳細闡述。

3.1 安裝

確認 recyclerView 支持庫已列在你的 app/build.gradle 中:

dependencies {
    ...
    compile 'com.android.support:recyclerview-v7:23.2.1'
}

3.2 定義一個 Model

每個 RecyclerView 背後都有一個數據集作為支撐。因此,我們定義一個 Contact 類,代表 RecyclerView 所使用的數據模型。

public class Contact {
    private String mName;
    private boolean mOnline;
    public Contact(String name, boolean online) {
        mName = name;
        mOnline = online;
    }
    public String getName() {
        return mName;
    }
    public boolean isOnline() {
        return mOnline;
    }
    private static int lastContactId = 0;
    public static ArrayList createContactsList(int numContacts) {
        ArrayList contacts = new ArrayList();
        for (int i = 1; i <= numContacts; i++) {
            contacts.add(new Contact("Person " + ++lastContactId, i <= numContacts / 2));
        }
        return contacts;
    }
}



3.3 創建 RecyclerView 的 layout

在 Activity 的布局 XML 文件中,添加一個 RecyclerView:



在布局的 preview 窗口中,我們將看到 Activity 中的 RecyclerView。

3.4 創建 Custom Row Layout

在創建 adapter 之前,我們需要先準備每一行所使用的 XML 布局文件。這裡我們嘗試創建一個水平方向的 LinearLayout,其中包含一個用於顯示名字的 TextView 和一個用於提醒該聯繫人的 Button:

這個布局文件可在 res/layout/item_contact.xml 中創建,並提供給每一行 item。注意,你應該為 layout_height 屬性使用 wrap_content,因為在 23.2.1 之前的版本中,RecyclerView 會忽略 layout 參數。



    
    

定義好自定義 item 布局後,我們就可以創建一個 adapter,把數據放置到 RecyclerView 中。

3.5 創建 RecyclerView.Adapter

接下來創建 adapter,它將負責把數據填充到 RecyclerView 中。Adapter 的角色,是將某個 position 上的對象轉換為列表中的一個 item 並插入其中。不過,這個 adapter 要求必須存在一個 ViewHolder 對象,用來描述並提供進入每一行所有視圖的入口。我們可以在 ContactsAdapter.java 中提供一個基本的空 adapter 和 holder:

// Create the basic adapter extending from RecyclerView.Adapter
// Note that we specify the custom ViewHolder which gives us access to our views
public class ContactsAdapter extends RecyclerView.Adapter {
    // Provide a direct reference to each of the views within a data item
    // Used to cache the views within the item layout for fast access
    public static class ViewHolder extends RecyclerView.ViewHolder {
        // Your holder should contain a member variable
        // for any view that will be set as you render a row
        public TextView nameTextView;
        public Button messageButton;
        // We also create a constructor that accepts the entire item row
        // and does the view lookups to find each subview
        public ViewHolder(View itemView) {
            // Stores the itemView in a public final member variable that can be used
            // to access the context from any ViewHolder instance.
            super(itemView);
            nameTextView = (TextView) itemView.findViewById(R.id.contact_name);
            messageButton = (Button) itemView.findViewById(R.id.message_button);
        }
    }
}

在定義好基本的 adapter 和 ViewHolder 之後,我們需要為 adapter 填充數據。首先,保存一個變量用於 contacts 列表,並通過構造器傳遞這個列表:

public class ContactsAdapter extends RecyclerView.Adapter {
    // ... view holder defined above...
    // Store a member variable for the contacts
    private List mContacts;
    // Store the context for easy access
    private Context mContext;
    // Pass in the contact array into the constructor
    public ContactsAdapter(Context context, List contacts) {
        mContacts = contacts;
        mContext = context;
    }
    // Easy access to the context object in the recyclerview
    private Context getContext() {
        return mContext;
    }
}



每個 adapter 都有 3 個基本方法:onCreateViewHolder 用於 inflate 一個 item 的布局並創建 holder;onBindViewHolder 用於根據數據設置視圖屬性;getItemCount 用於返回 items 的數量。我們需要實現這三個方法來完成 adapter:

public class ContactsAdapter extends RecyclerView.Adapter {
    // ... constructor and member variables
    // Usually involves inflating a layout from XML and returning the holder
    @Override
    public ContactsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);
        // Inflate the custom layout
        View contactView = inflater.inflate(R.layout.item_contact, parent, false);
        // Return a new holder instance
        ViewHolder viewHolder = new ViewHolder(contactView);
        return viewHolder;
    }
    // Involves populating data into the item through holder
    @Override
    public void onBindViewHolder(ContactsAdapter.ViewHolder viewHolder, int position) {
        // Get the data model based on position
        Contact contact = mContacts.get(position);
        // Set item views based on your views and data model
        TextView textView = viewHolder.nameTextView;
        textView.setText(contact.getName());
        Button button = viewHolder.messageButton;
        button.setText("Message");
    }
    // Returns the total count of items in the list
    @Override
    public int getItemCount() {
        return mContacts.size();
    }
}

adapter 完成後,剩下的工作就是把數據從 adapter 綁定到 RecyclerView。

3.6 綁定 Adapter 到 RecyclerView

在我們的 Activity 中,創建一個用戶集用於在 RecyclerView 中顯示:

public class UserListActivity extends AppCompatActivity {
    ArrayList contacts;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ...
        // Lookup the recyclerview in activity layout
        RecyclerView rvContacts = (RecyclerView) findViewById(R.id.rvContacts);
        // Initialize contacts
        contacts = Contact.createContactsList(20);
        // Create adapter passing in the sample user data
        ContactsAdapter adapter = new ContactsAdapter(this, contacts);
        // Attach the adapter to the recyclerview to populate items
        rvContacts.setAdapter(adapter);
        // Set layout manager to position the items
        rvContacts.setLayoutManager(new LinearLayoutManager(this));
        // That's all!
    }
}

最後,編譯運行,你將看到類似下圖的效果。如果你創建了足夠多的 items,當滾動這個列表時,這些視圖會被循環利用,滾動起來比 ListView 更加順暢。

3.7 通知 Adapter

與 ListView 不同,RecyclerView 沒有直接添加或刪除 item 的方法。你需要直接修改原始數據,並通知 Adapter 相應的修改。同時,在添加或刪除元素時,需要同步修改已存在的列表。例如,重新初始化下面的 contacts 列表並不會對 adapter 產生任何效果,因為它持有的仍是對舊列表內存的一個引用:

// do not reinitialize an existing reference used by an adapter
Contacts = Contact.createContactsList(5);

正確的做法是直接對已存在的引用進行操作:

// add to the existing list
Contacts.addAll(Contact.createContactsList(5));

有很多接口用於提醒 adapter 不同的修改:

Method 說明
notifyItemChanged(int pos) 通知 position 位置的 item 已經發生變化。
notifyItemInserted(int pos) 通知 position 位置新插入了一個 item。
notifyItemRemoved(int pos) 通知原先位於 position 的 item 已從數據集中移除。
notifyDataSetChanged() 通知整個數據集已發生變化,僅作為最後手段使用。

我們可以如下在 Activity 和 Fragment 中使用它們:

// Add a new contact
contacts.add(0, new Contact("Barney", true));
// Notify the adapter that an item was inserted at position 0
Adapter.notifyItemInserted(0);

每當我們想從 RecyclerView 添加或刪除 items 時,都需要明確地通知 adapter。與 ListView 的 adapter 不同,RecyclerView 的 adapter 不能僅依賴 notifyDataSetChanged(),而需要使用更細粒度的操作。

另外,如果你試圖更新一個已存在的列表,在進行任何修改前,請先確認當前 item 的數量。例如,應在 adapter 上調用 getItemCount() 來記錄即將修改的第一個 index:

// record this value before making any changes to the existing list
int curSize = adapter.getItemCount();
// replace this line with wherever you get new records
ArrayList newItems = Contact.createContactsList(20);
// update the existing list
contacts.addAll(newItems);
// curSize should represent the first element that got added
// newItems.size() represents the itemCount
Adapter.notifyItemRangeInserted(curSize, newItems.size());

3.8 滾動到新的 items

如果我們想在列表前面插入元素並讓它保持在最前面,可以將位置滾動到第 1 個元素:

adapter.notifyItemInserted(0);
rvContacts.scrollToPosition(0); // index 0 position

如果我們想在列表末尾添加 items 並希望滾動到底部,可以通知 adapter 有一個新元素被添加,並調用 RecyclerView 的 smoothScrollToPosition():

adapter.notifyItemInserted(contacts.size() - 1); // contacts.size() - 1 is the last element position
rvContacts.scrollToPosition(mAdapter.getItemCount() - 1); // update based on adapter

3.9 實現無限滾動

為了實現隨用戶滾動到底部時不斷加載更多數據的效果,可以使用 RecyclerView 的 addOnScrollListener(),並借助 EndlessScrollViewScrollListener 文檔添加一個 onLoadMore 方法。

4. 配置 RecyclerView

RecyclerView 是一個非常具有彈性、便於定制的控件,一些可用的選項如下。

4.1 性能

當所有 item 具有相同的高度和寬度時,可以讓滾動更加平滑:

recyclerView.setHasFixedSize(true);

4.2 布局

每個 item 的位置由 LayoutManager 配置。默認情況下,我們可以選擇 LinearLayoutManager、GridLayoutManager 和 StaggeredGridLayoutManager。Linear 可以讓 items 水平或垂直顯示:

// Setup layout manager for items
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// Control orientation of the items
// also supports LinearLayoutManager.HORIZONTAL
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
// Optionally customize the position you want to default scroll to
layoutManager.scrollToPosition(0);
// Attach layout manager to the RecyclerView
recyclerView.setLayoutManager(layoutManager);

使用 grid 或 staggered grid(交錯網格)也有類似操作:

// First param is number of columns and second param is orientation i.e Vertical or Horizontal
StaggeredGridLayoutManager gridLayoutManager =
    new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
// Attach the layout manager to the recycler view
recyclerView.setLayoutManager(gridLayoutManager);

例如,一個 staggered grid 將有如下顯示:

4.3 裝飾(Decorations)

我們可以使用多種裝飾來為 RecyclerView 的 items 添加修飾,比如 DividerItemDecoration:

RecyclerView.ItemDecoration itemDecoration =
    new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST);
recyclerView.addItemDecoration(itemDecoration);

這個 decorator 顯示的分界線效果如下圖:

4.3.2 網格間距裝飾

裝飾還可以用來為 grid layout 或 staggered grid 中 items 周圍添加相關的間距。你可以將 SpacesItemDecoration.java 複製到項目中,並通過 addItemDecoration 方法應用到 RecyclerView。

4.4 動畫(Animators)

RecyclerView 支持通過 ItemAnimator 為 item 提供進入、移動或刪除的動畫。默認的動畫由 DefaultItemAnimator 定義,它在 remove、move、add 等特殊操作中都有很好的表現。

目前實現 RecyclerView 動畫最快的方式是使用第三方庫。Third-party recyclerview-animators 庫包含了大量现成的動畫供你使用,無需自己動手創建。只需修改你的 app/build.gradle:

repositories {
    jcenter()
}
dependencies {
    compile 'jp.wasabeef:recyclerview-animators:2.2.0'
}

接著,我們就可以使用任何已定義的動畫來改變 RecyclerView 的行為:

recyclerView.setItemAnimator(new SlideInUpAnimator());

4.4.2 新的 ItemAnimator 接口

從支持 RecyclerView 的 support-v23.1.0 庫開始,ItemAnimator 接口提供了一個新的實現。舊接口已被標記為 deprecated,並更名為 SimpleItemAnimator。這個庫新增了一個 ItemHolderInfo 類,其表現與 DefaultItemAnimator 中定義的 MoveInfo 類相似,但被更普遍地用於在動畫過渡狀態中傳遞狀態信息。很可能在下一個版本的 defaultItemAnimator 中,會更簡潔地使用這個新類和新接口。

4.5 多樣化視圖(Heterogeneous Views)

如果你想在單個 RecyclerView 中 inflate 多種類型的 row,可以參考相關指南,它能幫助我們把包含多種不同類型 items 的內容添加到一個列表裡,效果如下圖:

當單個列表中需要包含大量不同類型的 items 時,這種設計非常有用。

4.6 處理觸摸事件

RecyclerView 允許我們使用下面的代碼處理 touch 事件:

recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
    @Override
    public void onTouchEvent(RecyclerView recycler, MotionEvent event) {
        // Handle on touch events here
    }
    @Override
    public boolean onInterceptTouchEvent(RecyclerView recycler, MotionEvent event) {
        return false;
    }
});

4.7 為 Items 綁定點擊處理器

4.7.1 使用 Decorator 綁定點擊監聽器

最早處理 RecyclerView item click handler 的方案是使用一個 decorator 類來管理 item click listener。有了這個 clever ItemClickSupport decorator 後,添加一個 click handler 就可以這樣寫:

ItemClickSupport.addTo(mRecyclerView).setOnItemClickListener(
    new ItemClickSupport.OnItemClickListener() {
        @Override
        public void onItemClicked(RecyclerView recyclerView, int position, View v) {
            // do it
        }
    }
);

在封裝之下,這個接口的實現細節會在後文描述。如果你使用了上面的代碼,就無需再做任何手動的 click handling。這個技術最原始的來歷可參考相關連結。

4.7.2 在 ViewHolder 中實現簡單的點擊處理器

RecyclerView 不像 ListView 那樣內置 setOnItemClickListener 來為 items 綁定點擊處理器。為了實現同樣的效果(替代上面使用 decorator 工具的方式),我們可以將 click event 綁定到 adapter 中的 ViewHolder 上:

public class ContactsAdapter extends RecyclerView.Adapter {
    // ...
    // Used to cache the views within the item layout for fast access
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView tvName;
        public TextView tvHometown;
        private Context context;
        public ViewHolder(Context context, View itemView) {
            super(itemView);
            this.tvName = (TextView) itemView.findViewById(R.id.tvName);
            this.tvHometown = (TextView) itemView.findViewById(R.id.tvHometown);
            // Store the context
            this.context = context;
            // Attach a click listener to the entire row view
            itemView.setOnClickListener(this);
        }
        // Handles the row being being clicked
        @Override
        public void onClick(View view) {
            int position = getLayoutPosition(); // gets item position
            User user = users.get(position);    // We can access the data within the views
            Toast.makeText(context, tvName.getText(), Toast.LENGTH_SHORT).show();
        }
    }
    // ...
}

如果我們想在按下 item 時顯示「selected」效果,可以給 row 的根 layout 設置 android:background 屬性為 ?android:attr/selectableItemBackground:



    

這將帶來如下圖所示的效果:

4.7.3 使用監聽器綁定點擊處理器

在實際應用中,你可能想在 RecyclerView 中為 view 設置 click handler,但把 click 的邏輯定義在 Activity 或 Fragment 中。為達到這個目的,可以在 adapter 中創建一個 custom listener,然後把事件向上傳遞給父級定義的接口實現:

public class ContactsAdapter extends RecyclerView.Adapter {
    // ...
    /***** Creating OnItemClickListener *****/
    // Define listener member variable
    private static OnItemClickListener listener;
    // Define the listener interface
    public interface OnItemClickListener {
        void onItemClick(View itemView, int position);
    }
    // Define the method that allows the parent activity or fragment to define the listener
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }
    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView tvName;
        public TextView tvHometown;
        public ViewHolder(final View itemView) {
            super(itemView);
            this.tvName = (TextView) itemView.findViewById(R.id.tvName);
            this.tvHometown = (TextView) itemView.findViewById(R.id.tvHometown);
            // Setup the click listener
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Triggers click upwards to the adapter on click
                    if (listener != null)
                        listener.onItemClick(itemView, getLayoutPosition());
                }
            });
        }
    }
    // ...
}

然後,我們可以如下為 adapter 綁定一個 click handler:

// In the activity or fragment
ContactsAdapter adapter = ...;
adapter.setOnItemClickListener(new ContactsAdapter.OnItemClickListener() {
    @Override
    public void onItemClick(View view, int position) {
        String name = users.get(position).name;
        Toast.makeText(UserListActivity.this, name + " was clicked!", Toast.LENGTH_SHORT).show();
    }
});

5. 實現下拉刷新

當 RecyclerView 需要通過向下拉的動作刷新內容時,應該使用 SwipeRefreshLayout。請參考關於 RecyclerView with SwipeRefreshLayout 的詳細指南,一步步實現下拉刷新。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved