如何修复分页以在RecyclerView中从服务器加载更多数据?

时间:2018-12-31 10:11:21

标签: java android android-recyclerview

我想从服务器加载更多数据。我应该得到firstItemId,因为该物品位于RecyclerView中。在listView中,我就是以此方式完成的。

listMain.setOnScrollListener( new AbsListView.OnScrollListener() {

    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }

    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {

        if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0) {

            if (lasttotal[getArguments().getInt( ARG_SECTION_NUMBER )] != totalItemCount) {
                lasttotal[getArguments().getInt( ARG_SECTION_NUMBER )] = totalItemCount;
                lastpage[getArguments().getInt( ARG_SECTION_NUMBER )]++;

                try {

                    JSONObject js_id = new JSONObject( view.getItemAtPosition( firstVisibleItem - 2 ).toString() );

                    static_id_news = js_id.getInt( "Id" );

                    if (getArguments().getInt( ARG_SECTION_NUMBER ) != 0)//"page=0&tagid="

                        new ApiNews( getActivity(), (ArrayAdapter) listMain.getAdapter(), rootView, ly_dialog ).execute( "id=" + static_id_news + "&tagid=" + newsnum[getArguments().getInt( ARG_SECTION_NUMBER )] + "&page=" + scroll_last_page + 1, 2 );
                    else
                        new ApiNewsPaper( getActivity(), (ArrayAdapter) listMain.getAdapter(), rootView, ly_dialog ).execute( lastpage[getArguments().getInt( ARG_SECTION_NUMBER )] );


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
});

现在,我想要与示例类似的示例,它将采用row的ID并将其发送以加载更多数据。谢谢。

1 个答案:

答案 0 :(得分:1)

尝试使用recyclerview的此解决方案

您应该使用recyclerview,它比listview更好,因为它的速度快,复杂度低且可自定义,例如交错视图

 private int pastVisiblesItems, visibleItemCount, totalItemCount;
 private boolean loading = true;

 recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (dy > 0) //check for scroll down
            {
                visibleItemCount = gridLayoutManager1.getChildCount();
                totalItemCount = gridLayoutManager1.getItemCount();
                pastVisiblesItems = gridLayoutManager1.findFirstVisibleItemPosition();

                if (loading) {
                    if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                        loading = false;
                        //Do pagination.. i.e. fetch new data
                    }
                }
            }
        }
    });

并根据您的api将加载设置为true,就像成功和失败的情况一样

loading = true;

其中gridLayoutManager1是布局管理器,它可能是linearlayoutgridlayout,具体取决于您的recyclerview

 recyclerViews.setLayoutManager(gridLayoutManager1);