来自Api的LoadMore Recycler View

时间:2017-10-26 12:11:07

标签: android android-recyclerview

我在Android中有Recycler视图,我需要在recycleler视图中实现更多加载,我在网上搜索但未能解决我的问题,这是我的代码请帮助

这是适配器

public class NewsReycelerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context context;
    List<String> Dates , Titles , Details , Images;
    public static String NewsDetail,NewsDate ,NewsTitle;
    public final int TYPE_NEWS = 0;
    public final int TYPE_LOAD = 1;
    private int visibleThreshold = 2;
    private int lastVisibleItem, totalItemCount;
    private boolean loading;
    private OnLoadMoreListener onLoadMoreListener;
    public NewsReycelerViewAdapter(RecyclerView recyclerView,Context context , List<String> stringsDate , List<String> stringTitles ,  List<String> stringDetails ,List<String> stringImage,final JPANewsFragment fragment) {

        this.context = context;
        this.Dates = stringsDate;
        this.Titles = stringTitles;
        this.Details = stringDetails;
        this.Images = stringImage;

        if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {

            final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);

                    totalItemCount = linearLayoutManager.getItemCount();
                    lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                    if (!loading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                        // End has been reached
                        // Do something
                        if (onLoadMoreListener != null) {
                            onLoadMoreListener.onLoadMore();
                        }
                        fragment.getHtmlNewsData("1");
                        loading = true;
                    }
                }
            });
        }
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);

        if(viewType==TYPE_NEWS){
            return new Item_Holder(inflater.inflate(R.layout.news_adapter_item,parent,false));
        }else{
            return new LoadHolder(inflater.inflate(R.layout.item_loading,parent,false));
        }


    }
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ((Item_Holder)holder).Date.setText(Dates.get(position));
        ((Item_Holder)holder).Title.setText(Titles.get(position));
        NewsDetail = Details.get(position);
        NewsDate = Dates.get(position);
        NewsTitle = Titles.get(position);
        ((Item_Holder)holder).itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity)context).changeFragmentMethod(new NewsDetailsFragment(),context.getResources().getString(R.string.news_details));
            }
        });



    }
    @Override
    public int getItemCount() {
        return Dates == null ? 0 : Dates.size();
    }



    //////////////////////////////////////////////////////////////////////////////////
    public class Item_Holder extends RecyclerView.ViewHolder {
        TextView Title , Date ;
        ImageView jpaThumbnail;
        public Item_Holder(View itemView) {
            super(itemView);
            Title = (TextView) itemView.findViewById(R.id.textView_title);
            Date = (TextView) itemView.findViewById(R.id.textView_date);
            jpaThumbnail = (ImageView) itemView.findViewById(R.id.thumbnail);

        }
    }
    static class LoadHolder extends RecyclerView.ViewHolder{
        public LoadHolder(View itemView) {
            super(itemView);
        }
    }

    @Override
    public int getItemViewType(int position) {
        return Dates.get(position) != null ? TYPE_NEWS : TYPE_LOAD;
    }

    public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
        this.onLoadMoreListener = mOnLoadMoreListener;
    }
    public void setLoaded() {
        loading = false;
    }


}

首先api有10个项目,当用户滑动时,我需要从另一个页面加载更多,

这是我主要活动中编写的代码

 newsReycelerViewAdapter = new NewsReycelerViewAdapter(recyclerViewNews,context, stringsDate, stringsTitle, stringsDetails,stringsImages,new JPANewsFragment());
                    recyclerViewNews.setLayoutManager(new LinearLayoutManager(context));
                    recyclerViewNews.setAdapter(newsReycelerViewAdapter);
                    loadingProgressBar.setVisibility(View.GONE);
                    newsReycelerViewAdapter.setLoaded();
                    newsReycelerViewAdapter.notifyDataSetChanged();

请让我知道如何解决这个问题。

3 个答案:

答案 0 :(得分:0)

我的loadmore功能如下:

private void loadMoreMessages() {

        DatabaseReference messageRef = mRootRef.child("messages").child(mThemaID);
        Query messageQuery = messageRef.orderByKey().endAt(mLastKey).limitToLast(10);


        messageQuery.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {

                Messages message = dataSnapshot.getValue(Messages.class);
String messageKey = dataSnapshot.getKey();


                if(!mPrevKey.equals(messageKey)){
                    messagesList.add(itemPos++, message);

                }else {

                    mPrevKey = mLastKey;
                }



                if(itemPos == 1){

                    mLastKey = messageKey;
                }



                mAdapter.notifyDataSetChanged();
                mLinearLayout.scrollToPositionWithOffset(itemPos-1, 0);

              mRefreshLayout.setRefreshing(false);


            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }

        });

    }

和听众:

mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    @Override
    public void onRefresh() {

        mCurrentPage++;

        itemPos = 0;

        loadMoreMessages();

    }
});

也许你可以用这个做点什么

答案 1 :(得分:0)

首先addOnScrollListener()添加RecyclerView并检测向下滚动

    recyclerViewNews.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (dy > 0) {
                Log.e("test","reached the last element of recyclerview");
                visibleItemCount = mLinearLayoutManager.getChildCount();
                totalItemCount = mLinearLayoutManager.getItemCount();
                pastVisiblesItems = mLinearLayoutManager.findFirstVisibleItemPosition();

                if (loading) {
                    if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                        loading = false;
                        fetchData();
                    }
                }
            }
        }
    });

创建函数fetchData()以向适配器添加更多数据 然后调用newsReycelerViewAdapter.notifyDataSetChanged();通知数据集更改并更改loading=true

在您的活动主要创建字段

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

答案 2 :(得分:0)

以下是使用从各种来源编译的简单库简单实施 LoadMore RecyclerView 的示例。

build.gradle

中添加此行
implementation 'com.hereshem.lib:awesomelib:2.0.1'

使用

在Activity中创建RecyclerView布局
<com.hereshem.lib.recycler.MyRecyclerView
        android:id="@+id/recycler"
        app:layoutManager="LinearLayoutManager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

通过传递支持

的类来创建ViewHolder
public static class EVHolder extends MyViewHolder<Events> {
    TextView date, title, summary;
    public EVHolder(View v) {
        super(v);
        date = v.findViewById(R.id.date);
        title = v.findViewById(R.id.title);
        summary = v.findViewById(R.id.summary);
    }
    @Override
    public void bindView(Events c) {
        date.setText(c.date);
        title.setText(c.title);
        summary.setText(c.summary);
    }
}

通过在适配器中传递项目,类和布局,创建具有极少行的项目列表变量和适配器

List<Events> items = new ArrayList<>();
MyRecyclerView recycler = findViewById(R.id.recycler);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, items, EVHolder.class, R.layout.row_event);
recycler.setAdapter(adapter);

可以使用以下行添加ClickListener和LoadMore Listener

recycler.setOnItemClickListener(new MyRecyclerView.OnItemClickListener() {
    @Override
    public void onItemClick(int position) {
        Toast.makeText(MainActivity.this, "Recycler Item Clicked " + position, Toast.LENGTH_SHORT).show();
    }
});

recycler.setOnLoadMoreListener(new MyRecyclerView.OnLoadMoreListener() {
    @Override
    public void onLoadMore() {
        loadData();
    }
});
loadData();

加载数据后,必须调用

recycler.loadComplete();

当不需要LoadMore时,可以通过调用

隐藏LoadMore布局
recycler.hideLoadMore();

可以找到完整示例here

希望这会有所帮助:)