这段时间项目需求,需要下拉刷新数据列表,此类控件已经有许多大神已经有博客和文章了,SwipeRefreshLayout+RecyclerView。思路是继承SwipeRefreshLayout,获取其子元素即数据列表控件,并监听列表控件的滚动事件,然后做出相应的处理。
public class SwipeRefreshLoadLayout extends SwipeRefreshLayout{
private RecyclerView recyclerView;
private OnLoadMoreListener onLoadMoreListener;
publicSwipeRefreshLoadLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onLayout(boolean changed,int left,int top,int right,int bottom) {
super.onLayout(changed, left, top, right, bottom);
if(recyclerView==null) {
if(getChildCount() >0) {
if(getChildAt(0) instanceof RecyclerView) {//獲取列表控件,可以是ListView
recyclerView= (RecyclerView) getChildAt(0);
OnScroll();
}
}
}
}
voidOnScroll(){
recyclerView.addOnScrollListener(newRecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView,int newState) {
super.onScrollStateChanged(recyclerView, newState);
LinearLayoutManager linearLayoutManager= (LinearLayoutManager) recyclerView.getLayoutManager();
//如果recyclerView当前在屏幕最底部的item的索引等于adapter的数据集长度,说明已经滑到了底部可以触发加载
if(linearLayoutManager.findLastCompletelyVisibleItemPosition()==recyclerView.getAdapter().getItemCount()-1){
onLoadMoreListener.onLoadMore();
}
}
});
}
public interface OnLoadMoreListener {
void onLoadMore();
}
public void setOnLoadMoreListener(SwipeRefreshLoadLayout.OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener= onLoadMoreListener;
}
}