该方法同样适用于LinearLayoutManager和GridLayoutManager,支持水平滑动和竖直滑动
OnLoadMoreListener.java
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
public abstract class OnLoadMoreListener extends RecyclerView.OnScrollListener {
private LinearLayoutManager layoutManager;
private int itemCount, lastPosition, lastItemCount;
public abstract void onLoadMore();
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
itemCount = layoutManager.getItemCount();
lastPosition = layoutManager.findLastCompletelyVisibleItemPosition();
} else {
Log.e("OnLoadMoreListener", "The OnLoadMoreListener only support LinearLayoutManager");
return;
}
if (lastItemCount != itemCount && lastPosition == itemCount - 1) {
lastItemCount = itemCount;
this.onLoadMore();
}
}
}
xml
<android.support.v7.widget.RecyclerView
android:id="@+id/themeRecyclerView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="bottom"
android:orientation="horizontal" />
Activity
BookThemeAdapter adapter;
int page = 1;
private void initData() {
getDataOnline();
adapter = new BookThemeAdapter(getContext(), 0, isDownloadDefaultOne);
themeRecyclerView.setAdapter(adapter);
themeRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
themeRecyclerView.setOnScrollListener(new OnLoadMoreListener() {
@Override
public void onLoadMore() {
//ToastUtils.showShort("加载更多");
Log.e(TAG, "onLoadMore");
++page;
getDataOnline();
}
});
}
private void getDataOnline() {
HttpRequest2.searchBookTheme(page).subscribe(new Subscriber<ListResult<BookTheme>>() {
@Override
public void onCompleted() {
if (progress_bar != null)
progress_bar.setVisibility(View.GONE);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(ListResult<BookTheme> bookThemeListResult) {
adapter.addData(bookThemeListResult.list);
adapter.notifyDataSetChanged();
}
});
}