注:本文網絡請求資料(包括采用OkHttp請求伺服器資料,用到的實體類都可根據實際項目進行替換)。
若後端沒有分頁接口(資料量不大)的情況下,可參考另一篇文章: 後端無分頁接口的情況.
請主要關注下拉重新整理和上拉加載(分頁)部分監聽功能的實作,網絡請求部分方法,可根據自己愛好進行替換
一、導入依賴
build.gradle(:app)
implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.1.0-alpha-14'
compile 'com.alibaba:fastjson:1.1.70.android'
implementation 'com.squareup.okhttp3:okhttp:3.9.0'
二、布局檔案(主要部分)
最外層總體布局是LinearLayout
<com.scwang.smartrefresh.layout.SmartRefreshLayout
android:id="@+id/refreshView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview_alldata"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="3dp"
android:layout_marginRight="3dp"
android:layout_marginBottom="3dp">
</androidx.recyclerview.widget.RecyclerView>
</com.scwang.smartrefresh.layout.SmartRefreshLayout>
三、activity 裡面實作功能
1、定義
activity的全局變量
private SmartRefreshLayout smartRefreshLayout;
private RecyclerView recyclerView_alldata;
private AllDataAdapter allDataAdapter;//自定義擴充卡
private List<DeviceData> deviceDataList=new ArrayList<>();;//存放請求到的所有資料集合
private List<CardDataEntity> cl;//要展示的卡片上的擴充卡資料集合
String baseUrl="網絡請求的url";
private Handler handler=new Handler();
private int totalPages=0;//請求裝置全部資料的總頁數
private boolean isreflesh=false;//資料是否在更新
int pagesize=10;//顯示資料每頁的條數
private int current_page = 1;//目前請求資料頁碼
2、擷取控件示例
activityde的onCreate方法裡面
recyclerView_alldata=findViewById(R.id.recyclerview_alldata);
smartRefreshLayout=findViewById(R.id.refreshView);
3、實作下拉重新整理、上拉加載(分頁)顯示資料
activity的onCreate方法裡面
//卡片展示裝置資料部分
recyclerView_alldata.setLayoutManager(new LinearLayoutManager(this));
//自定義網絡請求所有資料的方法,初始化資料,設定擴充卡
cl=new ArrayList<>();
allDataAdapter=new AllDataAdapter(cl);
recyclerView_alldata.setAdapter(allDataAdapter);
recyclerView_alldata.setItemAnimator(new DefaultItemAnimator());
initdeviceData(1);//網絡請求第一頁的資料
//下拉重新整理和上拉加載監聽
//設定下拉重新整理和上拉加載樣式,預設樣式
smartRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
smartRefreshLayout.setRefreshFooter(new ClassicsFooter(this));
//下拉重新整理和上拉加載更新資料
smartRefreshLayout.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
/**
* 下拉重新整理
* 重新向伺服器擷取第一頁資料
*/
@Override
public void onRefresh(@NonNull RefreshLayout refreshLayout) {
super.onRefresh(refreshLayout);
isreflesh=true;
current_page=1;//将目前頁數置為1
initdeviceData(current_page);//請求第一頁資料
recyclerView_alldata.smoothScrollToPosition(0);//回到頂部
smartRefreshLayout.finishRefresh(2000);
}
/**
* 上拉加載,請求下一頁資料
*/
@Override
public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
super.onLoadMore(refreshLayout);
isreflesh=true;
current_page++;//目前頁數加1
if (totalPages>=current_page){
Log.d(TAG, "上拉加載時候目前頁數與總頁數"+current_page+"/"+totalPages);
initdeviceData(current_page);
}else {
toastMessage("資料已全部加載完成!");
}
smartRefreshLayout.finishLoadMore(2000);
}
});
4、3裡面的網絡請求方法initdeviceData(int current_page)如下
/**
* 網絡請求資料
* @param current_page 分頁函數請求參數,目前頁碼
*/
public void initdeviceData(int current_page){
String newUrl="";
//pagesize為請求每頁的個數,請求url規則請根據實際項目進行撰寫
newUrl=baseUrl+"/"+current_page+"/"+pagesize;
Log.d(TAG, "請求的接口 "+newUrl);
//使用OkHttp進行請求
OkHttpClient okHttpClient=new OkHttpClient();
Request request=new Request.Builder()
.url(newUrl)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "請求情況response: "+response.toString());
dealWithResult(response.body().string(),current_page);//将請求到的内容傳到主線程進行處理
}
});
}
解析資料部分可參考另一篇文章
Android端使用FastJson解析從伺服器請求到的JSON串資料,轉為List<?>.
/**
* 處理網絡請求資料的函數
* @param res 網絡請求到的資料
* @param curr 目前請求頁碼
*/
private void dealWithResult(final String res,int curr) {
//在UI主線程操作
new Handler(getMainLooper()).post(new Runnable() {
@Override
public void run() {
Log.d(TAG, "請求到的全部資料:" + res);
List<DeviceData> jsonList=new ArrayList<>();
JSONObject object=JSONObject.parseObject(res);
JSONArray jsonArray=object.getJSONArray("records");//擷取請求結果中要用到的json資料
jsonList=JSON.parseArray(jsonArray.toJSONString(),DeviceData.class);
totalPages=object.getInteger("pages");//擷取請求結果中的頁數
Log.d(TAG, "總頁數: "+totalPages);
if (totalPages!=0){
showDeviceName.setText(jsonList.get(0).getDeviceDescription());//顯示裝置名稱
}
Log.d(TAG, "裝置名稱: "+showDeviceName.getText());
//請求頁碼為首頁時候,清空資料集合,重新指派
if (curr==1){
cl.clear();
}
for (int i=0;i<jsonList.size();i++){
DeviceData deviceData=jsonList.get(i);
CardDataEntity cardDataEntity=new CardDataEntity(deviceData.getDataType(),deviceData.getDataValue(),deviceData.getDeviceUnit(),deviceData.getUploadDate());
cl.add(cardDataEntity);
}
setData(cl);//更新adapter視圖
}
});
//重新整理資料和擴充卡視圖
public void setData(List<CardDataEntity> list){
this.cl=list;
allDataAdapter.notifyDataSetChanged();
}
四、用到的實體類(根據實際項目進行替換)
1、接收伺服器資料的Bean類DeviceData.class
/**
* 裝置資料實體類
*/
public class DeviceData {
//裝置id
String deviceId;
//裝置描述/名稱
String deviceDescription;
//資料類型,如溶氧含量、溫度、PH等
String dataType;
//資料值
String dataValue;
//資料機關
String deviceUnit;
//資料上傳時間
String uploadData;
public DeviceData() {
}
public DeviceData(String deviceId, String deviceDescription, String dataType, String dataValue, String deviceUnit, String uploadData) {
this.deviceId = deviceId;
this.deviceDescription = deviceDescription;
this.dataType = dataType;
this.dataValue = dataValue;
this.deviceUnit = deviceUnit;
this.uploadData = uploadData;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getDataValue() {
return dataValue;
}
public void setDataValue(String dataValue) {
this.dataValue = dataValue;
}
public String getDeviceUnit() {
return deviceUnit;
}
public void setDeviceUnit(String deviceUnit) {
this.deviceUnit = deviceUnit;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getDeviceDescription() {
return deviceDescription;
}
public void setDeviceDescription(String deviceDescription) {
this.deviceDescription = deviceDescription;
}
public String getUploadData() {
return uploadData;
}
public void setUploadData(String uploadData) {
this.uploadData = uploadData;
}
}
2、卡片展示的實體類,CardDataEntity.class
/**
* 全部資料中展示卡片部分用到的資料類
*/
public class CardDataEntity {
//資料類型,如溶氧含量、溫度、PH等
String dataType;
//資料值
String dataValue;
//資料機關
String deviceUnit;
//資料上傳時間
String uploadData;
public CardDataEntity() {
}
public CardDataEntity(String dataType, String dataValue, String deviceUnit, String uploadData) {
this.dataType = dataType;
this.dataValue = dataValue;
this.deviceUnit = deviceUnit;
this.uploadData = uploadData;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getDataValue() {
return dataValue;
}
public void setDataValue(String dataValue) {
this.dataValue = dataValue;
}
public String getDeviceUnit() {
return deviceUnit;
}
public void setDeviceUnit(String deviceUnit) {
this.deviceUnit = deviceUnit;
}
public String getUploadData() {
return uploadData;
}
public void setUploadData(String uploadData) {
this.uploadData = uploadData;
}
}