Android RecyclerView实现水平滑动,加载更多


该方法同样适用于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();
            }
        });

    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值