在MainActivity.Java中得到控件
swipeRefreshLayout = view.findViewById(R.id.swipe); recyclerView = view.findViewById(R.id.recy);
//上拉刷新 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { getData(); dataMyAdapter.notifyDataSetChanged(); swipeRefreshLayout.setRefreshing(false); } });
//上拉加载更多recycleview的监听
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
//当前RecyclerView显示出来的最后一个的item的position
int lastPosition = -1;
//当前状态为停止滑动状态SCROLL_STATE_IDLE时
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManager instanceof LinearLayoutManager) {
//得到最后一条数据
lastPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
}
//如果等于recycleview的最后一条,就加载数据
if (lastPosition == recyclerView.getLayoutManager().getItemCount() - 1) {
Toast.makeText(getActivity(), "滑动到底了", Toast.LENGTH_SHORT).show();
pager++;
getData();
}
}
}
});
想要上拉加载更多时将数据显示在底部,只需要在网络请求数据成功的方法中进行判断就可以了
public void getData() {
String path = "http://www.yulin520.com/a2a/impressApi/news/mergeList?sign=C7548DE604BCB8A17592EFB9006F9265&pageSize=20&gender=2&ts=1871746850&page=" + pager;
OkHttp3Utils.doGet(path, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String result = response.body().string();
System.out.println("==========result=====" + result.toString());
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Gson gson = new Gson();
MyDataJavaBean javaBean = gson.fromJson(result, MyDataJavaBean.class);
//判断pager页是不是第一条,重新实例化MyDataJavaBean bean;起一个其他的名字
if (pager == 1) {
bean = javaBean;
} else {
for (int i = 0; i < javaBean.getData().size(); i++) {
bean.getData().add(javaBean.getData().get(i));
}
}
if (dataMyAdapter == null) {
dataMyAdapter = new DataMyAdapter(javaBean, getActivity());
recyclerView.setAdapter(dataMyAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
} else {
dataMyAdapter.notifyDataSetChanged();
}
}
});
}
});
}