這次研究 RecyclerView 的下拉刷新實作,類似於 iOS 的UIRefreshControl 在 Android 中也有 SwipeRefreshLayout.
- 通過 GridLayoutManager 實現每一個 row 都顯示兩個 View 的排版。
- 當下拉 RecyclerView 的時候出現下拉刷新的動畫。
- 下拉刷新後隨即改變 RecyclerView 中的內容。
Components
- RecyclerView
- GridLayoutManager
- SwipeRefreshLayout
- CardLayout
PullToRequest
SwipeRefreshLayout
在 Android 中實現下拉加載很容易,可以直接在 layout 文件中將想要可以拉動的部分用 SwipeRefreshLayout 標籤包起來:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<android.support.v4.widget.SwipeRefreshLayout android:id="@+id/productsRefreshLayout" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView android:id="@+id/productRecyclerView" 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_toTopOf="parent" /> </android.support.v4.widget.SwipeRefreshLayout> |
建立一個下拉刷新的監聽方法
1 2 3 4 5 6 7 8 9 |
private val productsRefreshListener = SwipeRefreshLayout.OnRefreshListener{ // 模擬加載時間 Thread.sleep(200) val itemsCount = productsAdapter.products.size productsAdapter.products.add(ProductModel("Product ${itemsCount + 1}")) productsAdapter.notifyDataSetChanged() productsRefreshLayout.isRefreshing = false } |
設置一個 refresh 的監聽
1 |
productsRefreshLayout.setOnRefreshListener(productsRefreshListener) |
類似於 iOS 的 reloadData() 方法,我們通過對 Adapter 修改資料,並且通知他有變動並且可以更新了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
private val productsRefreshListener = SwipeRefreshLayout.OnRefreshListener{ // 模擬加載時間 Thread.sleep(200) // 增加內容 val itemsCount = productsAdapter.products.size productsAdapter.products.add(ProductModel("Product ${itemsCount + 1}")) // 刷新畫面 productsAdapter.notifyDataSetChanged() // 停止下拉動畫 productsRefreshLayout.isRefreshing = false } |
GridLayoutManager & CardView
這次不打算使用 LinearLayoutManager 顯示每一個 row 佔滿左右的 View 了,
而是使用 GridLayoutManager 來每一個 row 顯示兩個 View
我們給 layoutManager 設定每個 row 顯示兩個 CardView:
1 |
productRecyclerView.layoutManager = GridLayoutManager(this,2) |
CardView 是 Android 提供的一種卡片樣式,可以直接在 layout 中加入,也有一些基本屬性可以使用。
- CardView_cardBackgroundColor
- CardView_cardCornerRadius
- CardView_cardElevation
- CardView_cardMaxElevation
- CardView_cardPreventCornerOverlap
- CardView_cardUseCompatPadding
- CardView_contentPadding
- CardView_contentPaddingBottom
- CardView_contentPaddingLeft
- CardView_contentPaddingRight
- CardView_contentPaddingTop
筆記
- 問題:在初始化一些物件的時候,常常會用到 Context,不太明白為什麼。
比如 LinearLayoutManager(this),這裡的 this 就是 context - 問題:如何自己做一個 View 讓使用的人可以通過 layout 的 xml 來設定值?
還是說,xml 只是提供 variable 以及對應的 value ,然後通過 coding 方式來取用? - 有趣:SwipeRefreshLayout 只是在 layout 文件中將 RecyclerView 包起來就可以能監聽到下拉事件。
- TODO:之後可以在這篇中加入上拉加載的內容。
參考
- 官方文件 – CardView
- 官方文件 – SwipeRefreshLayout
- 可以到 Github 上看對應的 Source Code