溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android RecyclerView上拉加載和下拉刷新(基礎版)

發(fā)布時間:2020-08-30 00:07:38 來源:腳本之家 閱讀:979 作者:cnflyhz 欄目:移動開發(fā)

這里講述的是用谷歌原生的SwipeRefreshLayout,進行刷新,以及利用RecycleView的滾動事件,判斷是否到最后一個item,進行加載更多,這里加載更多是在RecycleView的適配器中使用不同item進行完成的。

這是activity的xml布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://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_progressStyle="@style/Material.Drawable.CircularProgress"
  app:pv_progressMode="indeterminate"
  android:layout_width="50dp"
  android:layout_height="50dp"
  android:visibility="gone"
  android:layout_centerInParent="true"/>
</RelativeLayout>

接下來是對應activity中的代碼:

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.retrofit.wangfei.viewpagertablayout.util.Constance;
import com.retrofit.wangfei.viewpagertablayout.R;
import com.retrofit.wangfei.viewpagertablayout.adapter.MyRecycleViewAdapter;
import com.rey.material.widget.ProgressView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


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; // 加載數(shù)據(jù)時顯示的進度圓圈
 private LinearLayoutManager mRecycleViewLayoutManager;

 private int mPageNum = 1;

 private List<String> lists = new ArrayList<>();
 private MyRecycleViewAdapter mAdapter;

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

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

 }

 @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;
 }

 /**在onCreateView方法后執(zhí)行*/
 @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);
 }

 /**進入頁面的初始化數(shù)據(jù)*/
 private void initData(){
  new Handler().postDelayed(new Runnable() {

   @Override
   public void run() {
    netNewsList(true);
    progress_loading_main.setVisibility(View.GONE);
   }
  }, 2000);
 }

 /**RecyclerView每個item的點擊事件*/
 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() {
//  recyclerview.setItemAnimator(new DefaultItemAnimator());
//  recyclerview.setHasFixedSize(true);
  mRecycleViewLayoutManager = new LinearLayoutManager(getActivity());
  recyclerview.setLayoutManager(mRecycleViewLayoutManager); // 設置RecycleView,顯示是ListView還是gridView還是瀑布流

 }

 /**下拉刷新*/
 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);
   }
  });
 }

 /**
  * 設置上拉加載更多
  *
  * @param adapter RecyclerView適配器
  */
 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) { // 真實開發(fā)中要設置mNews.size()大于加載分頁顯示的個數(shù)
      adapter.loadLayout.setVisibility(View.VISIBLE);
      //加載更多
      new Handler().postDelayed(new Runnable() {

       @Override
       public void run() {
        netNewsList(false);
       }
      }, 2000);
     }
    }
   }
  });
 }

 /**
  * 從網(wǎng)絡加載數(shù)據(jù)列表
  *
  * @param isRefresh 是否刷新 true 為刷新,false為不刷新
  */
 private void netNewsList(boolean isRefresh) {
//  viewDelegate.showLoading();
  if (isRefresh) {
   mPageNum = 1;
  } else {
   mPageNum++;
  }

  if (isRefresh) {
   if (!lists.isEmpty()) {
    lists.clear();
   }
  }
  // TODO 這里把頁數(shù)mPageNum上傳到服務端
  lists.clear();
  lists.addAll(getData());
  mAdapter.notifyDataSetChanged();
 }

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

接下來是RecycleView適配器中的xml文件:

這是正常item的布局,至于用CardView是為了讓item展示出來的效果更好看

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://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>

這是現(xiàn)實上拉加載的布局文件,作為不同item共同展示在RecycleView上面:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://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_progressStyle="@style/Material.Drawable.CircularProgress"
  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>

下面我們看看RecycleView適配器的寫法:

import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.retrofit.wangfei.viewpagertablayout.R;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Android Studio
 * Description: RecycleView的適配器
 */
public class MyRecycleViewAdapter extends RecyclerView.Adapter {

 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);
   ItemViewHolder itemViewHolder = new ItemViewHolder(view);
   return itemViewHolder;
  } 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) {
   String text = lists.get(position);
   ItemViewHolder itemHolder = (ItemViewHolder) holder;
   itemHolder.text.setText(text);
  }
 }

 @Override
 public int getItemCount() {
  return lists.size() + 1;
 }

 @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);
  }
 }

 /**調(diào)到外部使用*/
 public void setOnItemClickListener(OnItemClickListener onItemClickListener){
  this.mOnItemClickListener = onItemClickListener;
 }

 /**定義接口*/
 public interface OnItemClickListener{
  void onItemClick(View v,int position);
 }
}


最后是刷新控件的4個不同顏色:

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'

到這里就結束了,完成了下拉刷新和上拉加載更多的實現(xiàn)。

下面說說RecyclerView的使用最基礎的三點:

一:

recyclerview.setHasFixedSize(true); 
//方法用來使RecyclerView保持固定的大小,該信息被用于自身的優(yōu)化。

二:

recyclerview.setItemAnimator(new DefaultItemAnimator());
ItemAnimator會根據(jù)適配器上收到的通知動畫顯示視圖組的修改?;旧希鼤詣语@示添加和移除條目動畫。這也不是一個簡單的類,但我們發(fā)現(xiàn)DefaultItemAnimator已經(jīng)可以運行得很好了。

三:

recyclerview.setLayoutManager(mRecycleViewLayoutManager); 

// 設置RecycleView,顯示是ListView還是gridView還是瀑布流。

// 顯示是ListView 
LinearLayoutManager mRecycleViewLayoutManager = new LinearLayoutManager(context);

// 顯示是gridView,參數(shù)一:上下文,參數(shù)二:列數(shù) 
GridLayoutManager mGridLayoutManager=new GridLayoutManager(context, 4);

// 顯示是瀑布流,參數(shù)一:顯示幾列,參數(shù)二:現(xiàn)實的方向,垂直或水平 
StaggeredGridLayoutManager mStaggeredGridLayoutManager=new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);

更多詳細請參考:Android RecyclerView藝術般的控件使用完全解析

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI