SwipeRefreshLayout是google官方的刷新加载框架,基本使用:
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/common_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/common_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout>
swipeRefreshLayout.setColorSchemeColors(Color.BLUE,
Color.RED, Color.BLUE);//设置加载颜色
SwipeRefreshLayout中可以加RecyclerView或者ListView,如果还需要添加头部底部,可以在ListView或者Recyclerview中实现。
默认只提供了OnRefreshListener即下拉刷新:
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
presenter.requestData();
}
});
swipeRefreshLayout.setRefreshing(false);//设置加载或者停止加载
如果需要添加上拉加载,则要监听Recyclerview或者ListView的滚动位置来进行判断是否可以进行加载,这里只说Recyclerview:
我们需要获取recyclerview的LayoutManger来获取一些需要的值,lastVisibleItemPosition是可见的最底下的item,visibleItemCount 是当前屏幕item count,totalItemCount 是总item个数,state 是滚动状态,这里的判断逻辑是:
如果当前屏幕有可见item,可见的最后一个item的position等于总个数-1,并且处于滚动停止状态,则判断可以加载
private boolean canLoadMore(){
LinearLayoutManager layoutManager = (LinearLayoutManager) homeRecycler.getLayoutManager();
int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
int visibleItemCount = layoutManager.getChildCount();
int totalItemCount = layoutManager.getItemCount();
int state = homeRecycler.getScrollState();
if (visibleItemCount > 0 && (lastVisibleItemPosition == totalItemCount - 1) && state == homeRecycler.SCROLL_STATE_IDLE){
return true;
}
return false;
}
recyclerview监听滚动位置:
recyclerview监听滚动位置也是通过获取recyclerview的layoutManger
这里是通过判断position类型来改变toolbar标题
LinearLayoutManager linearLayoutManager = (LinearLayoutManager)homeRecycler.getLayoutManager();
int nowPosition = linearLayoutManager.findFirstVisibleItemPosition();
if (adapter.getItemViewType(nowPosition) == HomeRecyclerAdapter.TYPE_GROUP){
if (nowPosition == 1){
activity.toolbar.setTitle(getString(R.string.home_time_default_str));
}else {
activity.toolbar.setTitle(DateUtil.getCurrentStringStr(newsStories.get(nowPosition).getDate()));
}
}else if (adapter.getItemViewType(nowPosition) == HomeRecyclerAdapter.TYPE_BANNER){
activity.toolbar.setTitle(getString(R.string.home_toolbar_title));
}