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

RecyclerView 下拉刷新與上拉加載more:基礎版實作

編輯:關於 Android 程式設計

這裡示範最直白的做法:刷新交給 Google 原生的 SwipeRefreshLayout,加載更多則靠 RecyclerView 的捲動事件判斷是否已到最後一項,並在 Adapter 中以不同類型的 item 呈現底部的「正在加載」提示。

一、版面配置

 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
 xmlns:app="https://schemas.android.com/apk/res-auto"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">

 <android.support.v4.widget.SwipeRefreshLayout
 android:id="@+id/swipe_refresh_layout"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >
 <android.support.v7.widget.RecyclerView
 android:id="@+id/recyclerview"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#F0F0F0"
 android:clipToPadding="false"
 android:paddingBottom="16dp"
 android:paddingTop="16dp"/>
 </android.support.v4.widget.SwipeRefreshLayout>

 <com.rey.material.widget.ProgressView
 android:id="@+id/progress_loading_main"
 app:pv_autostart="true"
 app:pv_circular="true"
 app:pv_progress
 app:pv_progressMode="indeterminate"
 android:layout_width="50dp"
 android:layout_height="50dp"
 android:visibility="gone"
 android:layout_centerInParent="true"/>
 </RelativeLayout>

二、Activity 邏輯

 public class HomeFragment extends Fragment {
 @Bind(R.id.recyclerview) RecyclerView recyclerview;
 @Bind(R.id.swipe_refresh_layout) SwipeRefreshLayout swipeRefreshLayout;
 @Bind(R.id.progress_loading_main) ProgressView progress_loading_main;

 private LinearLayoutManager mRecycleViewLayoutManager;
 private int mPageNum = 1;
 private List<String> lists = new ArrayList<>();
 private MyRecycleViewAdapter mAdapter;

 public static HomeFragment newInstance() {
 return new HomeFragment();
 }

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 View view = inflater.inflate(R.layout.fragment_home, container, false);
 ButterKnife.bind(this, view);
 return view;
 }

 @Override
 public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
 super.onViewCreated(view, savedInstanceState);
 mAdapter = new MyRecycleViewAdapter(lists, getActivity());
 initRecyclerView();
 swipeRefreshLayout.setColorSchemeResources(Constance.colors);
 recyclerview.setAdapter(mAdapter);
 recyclerViewOnItemClickListener();
 refresh();
 loadMore(mAdapter);
 progress_loading_main.setVisibility(View.VISIBLE);
 initData();
 }

 @Override
 public void onDestroyView() {
 super.onDestroyView();
 ButterKnife.unbind(this);
 }

 /** 進入頁面的初始資料載入 */
 private void initData() {
 new Handler().postDelayed(new Runnable() {
 @Override
 public void run() {
 netNewsList(true);
 progress_loading_main.setVisibility(View.GONE);
 }
 }, 2000);
 }

 /** RecyclerView 每一項的點擊事件 */
 private void recyclerViewOnItemClickListener() {
 mAdapter.setOnItemClickListener(new MyRecycleViewAdapter.OnItemClickListener() {
 @Override
 public void onItemClick(View view, int position) {
 Snackbar.make(view, "fly", Snackbar.LENGTH_SHORT).show();
 }
 });
 }

 /** 初始化 RecyclerView */
 private void initRecyclerView() {
 mRecycleViewLayoutManager = new LinearLayoutManager(getActivity());
 recyclerview.setLayoutManager(mRecycleViewLayoutManager);
 }

 /** 下拉刷新 */
 private void refresh() {
 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
 @Override
 public void onRefresh() {
 new Handler().postDelayed(new Runnable() {
 @Override
 public void run() {
 netNewsList(true);
 swipeRefreshLayout.setRefreshing(false);
 }
 }, 2000);
 }
 });
 }

 /** 上拉加載更多 */
 public void loadMore(final MyRecycleViewAdapter adapter) {
 recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
 private int lastVisibleItem;

 @Override
 public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
 super.onScrolled(recyclerView, dx, dy);
 lastVisibleItem = mRecycleViewLayoutManager.findLastVisibleItemPosition();
 }

 @Override
 public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
 super.onScrollStateChanged(recyclerView, newState);
 // 只在停止滑動時處理,否則容易出現重繪異常
 if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {
 if (lists != null && lists.size() >= 10) {
 adapter.loadLayout.setVisibility(View.VISIBLE);
 new Handler().postDelayed(new Runnable() {
 @Override
 public void run() {
 netNewsList(false);
 }
 }, 2000);
 }
 }
 }
 });
 }

 /**
 * 從網路載入列表
 * @param isRefresh true 為刷新,false 為加載更多
 */
 private void netNewsList(boolean isRefresh) {
 if (isRefresh) {
 mPageNum = 1;
 } else {
 mPageNum++;
 }
 if (isRefresh && !lists.isEmpty()) {
 lists.clear();
 }
 // 實務上把 mPageNum 傳到伺服器
 lists.clear();
 lists.addAll(getData());
 mAdapter.notifyDataSetChanged();
 }

 private List<String> getData() {
 for (int i = 0; i < 10; i++) {
 list.add(i + "");
 }
 return list;
 }
 }

三、Adapter 的兩種 item 布局

一般項目用 CardView 讓視覺更有層次:

 <?xml version="1.0" encoding="utf-8"?>
 <android.support.v7.widget.CardView xmlns:android="https://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="wrap_content">
 <TextView
 android:id="@+id/text"
 android:layout_width="match_parent"
 android:layout_height="50dp"
 android:text=""
 android:gravity="center"/>
 </android.support.v7.widget.CardView>

底部提示列作為第二種 item,預設隱藏:

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
 xmlns:app="https://schemas.android.com/apk/res-auto"
 android:id="@+id/load_layout"
 android:visibility="gone"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:gravity="center"
 android:orientation="horizontal"
 android:paddingBottom="12dip"
 android:paddingTop="12dip">
 <com.rey.material.widget.ProgressView
 app:pv_autostart="true"
 app:pv_circular="true"
 app:pv_progress
 app:pv_progressMode="indeterminate"
 android:layout_width="24dp"
 android:layout_height="24dp" />
 <TextView
 android:id="@+id/more_data_msg"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:textSize="16sp"
 android:layout_marginLeft="10dp"
 android:text="正在加載..." />
 </LinearLayout>

Adapter 端靠 getItemViewType() 區分兩種型別,並在 onCreateViewHolder() 中分別 inflate:

 public class MyRecycleViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
 private final static int TYPE_ITEM = 0X01;
 private final static int TYPE_FOOTER = 0x02;

 private List<String> lists;
 private Activity context;
 public LinearLayout loadLayout;
 private OnItemClickListener mOnItemClickListener;

 public MyRecycleViewAdapter(List<String> lists, Activity context) {
 this.lists = lists;
 this.context = context;
 }

 @Override
 public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
 if (TYPE_ITEM == viewType) {
 View view = LayoutInflater.from(parent.getContext())
 .inflate(R.layout.recycle_view_item, parent, false);
 return new ItemViewHolder(view);
 } else {
 View view = LayoutInflater.from(parent.getContext())
 .inflate(R.layout.list_footer, parent, false);
 loadLayout = (LinearLayout) view.findViewById(R.id.load_layout);
 return new FootViewHolder(view);
 }
 }

 @Override
 public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
 if (holder instanceof ItemViewHolder) {
 ItemViewHolder itemHolder = (ItemViewHolder) holder;
 itemHolder.text.setText(lists.get(position));
 }
 }

 @Override
 public int getItemCount() {
 return lists.size() + 1; // 多算 footer 一項
 }

 @Override
 public int getItemViewType(int position) {
 if (position + 1 == getItemCount()) {
 return TYPE_FOOTER;
 } else {
 return TYPE_ITEM;
 }
 }

 public class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
 @Bind(R.id.text) TextView text;

 public ItemViewHolder(View itemView) {
 super(itemView);
 ButterKnife.bind(this, itemView);
 itemView.setOnClickListener(this);
 }

 @Override
 public void onClick(View v) {
 mOnItemClickListener.onItemClick(v, getPosition());
 }
 }

 public class FootViewHolder extends RecyclerView.ViewHolder {
 public FootViewHolder(View itemView) {
 super(itemView);
 }
 }

 public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
 this.mOnItemClickListener = onItemClickListener;
 }

 public interface OnItemClickListener {
 void onItemClick(View v, int position);
 }
 }

刷新控件的四色循環設定:

 public interface Constance {
 /** 下拉刷新控件變化的四個顏色 */
 int[] colors = new int[] {
 android.R.color.holo_green_light,
 android.R.color.holo_blue_light,
 android.R.color.holo_green_light,
 android.R.color.holo_blue_light
 };
 }

相依套件:

 compile 'com.android.support:appcompat-v7:23.3.0'
 compile 'com.android.support:design:23.3.0'
 compile 'com.jakewharton:butterknife:7.0.1'
 compile 'com.android.support:support-v4:23.3.0'
 compile 'com.google.android.gms:play-services:8.4.0'
 compile 'com.github.rey5137:material:1.2.2'

四、RecyclerView 的三個基礎設定

1. setHasFixedSize(true):告知 RecyclerView 自身尺寸不變,可用於內部優化。

2. setItemAnimator(new DefaultItemAnimator()):ItemAnimator 會依 Adapter 收到的通知播放增刪動畫,DefaultItemAnimator 在實務上表現已經足夠好。

3. setLayoutManager():決定呈現形態。

 // 列表
 LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(context);
 // 網格,參數為上下文與欄數
 GridLayoutManager mGridLayoutManager = new GridLayoutManager(context, 4);
 // 瀑布流,參數為欄數與方向
 StaggeredGridLayoutManager mStaggeredGridLayoutManager =
 new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved