如何使用Recycleview无限滚动加载?

时间:2018-01-13 05:19:36

标签: android android-recyclerview

如何使用Recycleview

无限滚动加载

当用户滚动动态数据自动获取和显示时,如何显示无限的结果。因此加载时间消耗,应用程序将正常工作。

文件名: MainActivity.java //我要显示的主要Java文件加载更多

        package com.ejobbox.ejobbox;

        import android.os.Bundle;
        import android.support.v7.app.AppCompatActivity;
        import android.support.v7.widget.LinearLayoutManager;
        import android.support.v7.widget.RecyclerView;
        import android.text.format.DateFormat;
        import android.util.Log;
        import android.view.View;
        import android.widget.ProgressBar;

        import java.util.ArrayList;
        import java.util.List;
        import retrofit2.Call;
        import retrofit2.Callback;
        import retrofit2.Response;
        import retrofit2.Retrofit;
        import retrofit2.converter.gson.GsonConverterFactory;

        public class MainActivity extends AppCompatActivity {

            private RecyclerView recyclerView;
            private ProgressBar progressBar;
            private LinearLayoutManager mLayoutManager;
            private RecyclerViewAdapter adapter;
            private ArrayList<Model> list;
            private String baseURL="http://mywebsite.com/";
            public static List<WPPost> mListPost;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                recyclerView= findViewById(R.id.recycler_view);
                progressBar=findViewById(R.id.progressbar);

                mLayoutManager=new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL,false);
                recyclerView.setLayoutManager(mLayoutManager);

                list=new ArrayList<Model>();
                // call retrofit

                getRetrofit();

                adapter=new RecyclerViewAdapter(list,MainActivity.this);
                recyclerView.setAdapter(adapter);

            }

            private void getRetrofit(){
                Retrofit retrofit=new Retrofit.Builder()
                        .baseUrl(baseURL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
                RetrofitArrayApi service = retrofit.create(RetrofitArrayApi.class);
               Call<List<WPPost>> call= service.getPostInfo();
               call.enqueue(new Callback<List<WPPost>>() {

                   @Override
                   public void onResponse(Call<List<WPPost>> call, Response<List<WPPost>> response) {
                       Log.e("mainactivty","response"+ response.body());
                       progressBar.setVisibility(View.GONE);

                       for(int i=0; i<response.body().size();i++){

                           Log.e ("main","Title"+ response.body().get(i).getTitle().getRendered()+"  "+
                                        response.body().get(i).getId());

                           String tempdetails=response.body().get(i).getExcerpt().getRendered().toString();
                           tempdetails=tempdetails.replace("<p>","");
                           tempdetails=tempdetails.replace("</p>","");
                           String linkdetail=response.body().get(i).getLink().toString();

                           String date=response.body().get(i).getDate().toString();

                           list.add(new Model(Model.IMAGE_TYPE, response.body().get(i).getTitle().getRendered(),
                                   tempdetails,date,
                                   response.body().get(i).getLinks().getWpFeaturedmedia().get(0).getHref(),linkdetail) );
                       }
                       adapter.notifyDataSetChanged();
                   }

                   @Override
                   public void onFailure(Call<List<WPPost>> call, Throwable t) {

                   }
               });
            }
        }

这是我定义了recyclear视图适配器的RecyclearViewAdapter。

文件名: RecyclearViewAdapter.java // Recyclear View Adapter File

    package com.ejobbox.ejobbox;

    import android.content.Context;
    import android.content.Intent;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import android.widget.TextView;

    import java.util.ArrayList;

    public class RecyclerViewAdapter extends RecyclerView.Adapter{
        private ArrayList<Model> dataset;
        private Context mContext;

        public RecyclerViewAdapter(ArrayList<Model> mlist, Context context) {
          this.dataset=mlist;
          this.mContext=context;
        }

        public static class ImageTypeViewHolder extends RecyclerView.ViewHolder{
            TextView title,subtitle,link,date;
            ImageView imageView;

            public ImageTypeViewHolder(View itemView){
                super(itemView);
                this.title=(TextView)itemView.findViewById(R.id.title);
                this.link=(TextView)itemView.findViewById(R.id.link);
                this.subtitle=(TextView) itemView.findViewById(R.id.subtitle);
                this.imageView=(ImageView) itemView.findViewById(R.id.icon);
                this.date=(TextView)itemView.findViewById(R.id.date);
            }
        }
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.postdetails,parent,false);
            return new ImageTypeViewHolder(view);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final Model object=dataset.get(position);


            ((ImageTypeViewHolder) holder).title.setText(object.title);
            ((ImageTypeViewHolder) holder).subtitle.setText(object.subtitle);
            //((ImageTypeViewHolder) holder).link.setText(object.link);
            ((ImageTypeViewHolder) holder).date.setText((CharSequence) object.date);

            ((ImageTypeViewHolder) holder).title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Intent intent=new Intent(mContext, WPPostDetails.class);
                    intent.putExtra("itemPosition",position);

                    intent.putExtra("link",object.link.toString());
                    mContext.startActivity(intent);

                }
            });

        }

        @Override
        public int getItemCount() { return dataset.size();}
    }

3 个答案:

答案 0 :(得分:1)

不要使用无限滚动它不能按预期工作。

您可以使用此

        recyclerView.addOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {


            if (isLastItemDisplaying())
            {
                scrollCount=scrollCount+10;
                L.v("scroll count",""+recyclerView.getAdapter().getItemCount());
                loadMoreItems(scrollCount);

            }

            }
        });

private boolean isLastItemDisplaying()
{
    if (storiesList.getAdapter().getItemCount()!=0) {
        int last_visible_count=manager.findFirstCompletelyVisibleItemPosition();
        if (last_visible_count!=RecyclerView.NO_POSITION && last_visible_count==storiesList.getAdapter().getItemCount()-1) {
            return true;
        }
    }
    return false;
}

在这个loadMoreItems方法中调用你的api。确保在每次api调用时将此滚动计数发送到您的服务器。并且在sql查询中您必须执行此操作

EX: 例如,第一次计数为0; SELECT * FROM posts LIMIT 0,10

在Scroll上你的scrollCount值会增加10(你可以使用你的值滚动计数值来获取接下来的10行)

SELECT * FROM帖子LIMIT 10,10

答案 1 :(得分:0)

您只需将新数据添加到列表电影的最后位置,一切都会正常工作。为此 -

创建一个新的列表&lt; Model&gt;列表newList 并将更新后的数据添加到其中。现在将 newList 添加到列表并通知适配器。就像下面一样 -

  List<Model> newList = new ArrayList<>();

  // your code..

  recyclerView.addOnScrollListener(new EndlessScrollListener(mLayoutManager) {
        @Override
        public void onLoadMore(int page, int totalItemsCount) {
            loadingMore=true;
            getRetrofit();

            int currentSize = adapter.getItemCount();
            list.addAll(newList);
            adapter.notifyItemRangeInserted(currentSize, list.size() - 2);
        }
    });

在这里,您可以找到 EndlessScrollListener 类。

请查看我的其他相关答案以了解更多详情 -

How to load more items in a ListView using AsyncTask or any other method

Continious scrolling in recyclerview by Json request and adding new item with previous

希望它会有所帮助。

答案 2 :(得分:0)

以下是使用从各种来源编译的简单库简单实施 Endless Scrolling 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

希望这会有所帮助:)