Android Recyclerview无限滚动

时间:2018-09-22 20:18:14

标签: android android-recyclerview android-volley

我想使用Adapters和RecyclerViews 无休止地滚动代码,我正在使用 Volley JSON 提取我的商品。尽管我已经阅读了这些指南(Codepath和github),但发现将其应用于自己的场景很困难。

  

我的json具有以下格式:

[{"id":"9","title":"Shokungeki no Souma","ano":"2016","categoria":"A\u00e7\u00e3o, Drama, Super Poderes, Vida Escolar, Romance","capa":"http:\/\/localhost:8080\/image\/2cc4dea4df2797c797615a0c7767878c1524864330_full.jpg","sinopse":"Obrigado e um canal de comunica\u00e7\u00e3o e marketing e comunica\u00e7\u00e3o visual e decidi que vou fazer"},{"id":"10","title":"Fate\/Stay Night","ano":"2006","categoria":"A\u00e7\u00e3o, Drama, Super Poderes, Vida Escolar, Romance","capa":"http:\/\/localhost:8080\/image\/IMG-20180912-WA0000.jpg","sinopse":"Obrigado e um canal de comunica\u00e7\u00e3o"},{"id":"11","title":"Sword Art Online","ano":"2015","categoria":"A\u00e7\u00e3o, Drama, Super Poderes, Vida Escolar, Romance","capa":"http:\/\/localhost:8080\/image\/FB_IMG_15366178545093060.jpg","sinopse":"Obrigado e um abra\u00e7o e at\u00e9 amanh\u00e3 de noite de sono \u00e9 um canal do le\u00e3o e Castela um abra\u00e7o a todas que est\u00e3o na mesma situa\u00e7\u00e3o e n\u00e3o consegui abrir"},{"id":"8","title":"Charlotte","ano":"2015","categoria":"A\u00e7\u00e3o, Drama, Super Poderes, Vida Escolar, Romance","capa":"http:\/\/localhost:8080\/image\/f67a9d25f1a79891bd8cc9e68bf6021c1435186459_full.jpg","sinopse":"Um n\u00famero muito reduzido de adolescentes possui poderes sobrenaturais. No entanto, todos esses poderes s\u00e3o imperfeitos, tendo, por isso, uma utilidade muito limitada. Otosaka Yuu \u00e9 um desses jovens e usa a sua habilidade de possuir outras pessoas por cinco segundos para ter uma vida escolar satisfat\u00f3ria e entrar numa escola prestigiosa, possuindo os melhores alunos e copiando-os. Contudo, certo dia \u00e9 denunciado por Tomori Nao, que tamb\u00e9m possui poderes e \u00e9 presidente da Associa\u00e7\u00e3o de Estudantes da Academia Hoshinoumi, institui\u00e7\u00e3o destinada \u00e0queles com habilidades sobrenaturais. O seu encontro leva Yuu a transferir-se para a Academia Hoshinoumi e, assim, a descobrir o duro destino daqueles que possuem poderes."}]

以下是我正在使用的代码:

  

片段:

public class AllFragment extends Fragment {
    private RecyclerView recyclerView;
    private AVLoadingIndicatorView avi;
    private GridLayoutManager gridLayoutManager;
    private Data2Adapter adapter;
    private List<Data> data_list;

    Boolean isScrolling = false;
    int currentItems, totalItems, scrollOutItems;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_all, container, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_all);
        avi = (AVLoadingIndicatorView) view.findViewById(R.id.fragmentallProgress);
        data_list  = new ArrayList<>();
        load_data_from_server(0);
        avi.show();

        gridLayoutManager = new GridLayoutManager(getContext(),2);
        recyclerView.setLayoutManager(gridLayoutManager);

        adapter = new Data2Adapter(getContext(),data_list);
        recyclerView.setAdapter(adapter);

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


                }
            });

        return view;

    }
    private void load_data_from_server(int id) {
        String url = "http://localhost:8000/getanimes.php?filter=#";
        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try
                    {
                        JSONArray array = new JSONArray(response);


                    for (int i=0; i<array.length(); i++){

                        JSONObject object = array.getJSONObject(i);

                        Data data = new Data(object.getInt("id"),object.getString("title"),
                                             object.getString("capa"));

                        data_list.add(data);


                    }
                    }
                    catch (JSONException e)
                    {}


                    adapter.notifyDataSetChanged();
                    avi.hide();

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getContext(), "Ocorreu um erro inesperado!", Toast.LENGTH_SHORT).show();

                }
            });
        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);

    }


}
  

适配器:

public class Data2Adapter extends RecyclerView.Adapter<Data2Adapter.ViewHolder> {

    private Context context;
    private List<Data> my_data;

    public Data2Adapter(Context context, List<Data> my_data) {
        this.context = context;
        this.my_data = my_data;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.anim_grid,parent,false);

        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        holder.description.setText(my_data.get(position).getTitle());
        Glide.with(context).load(my_data.get(position).getCapa()).into(holder.imageView);

    }

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

    public  class ViewHolder extends  RecyclerView.ViewHolder{

        public TextView description;
        public ImageView imageView;

        public ViewHolder(View itemView) {
            super(itemView);
            description = (TextView) itemView.findViewById(R.id.textview7);
            imageView = (ImageView) itemView.findViewById(R.id.imageview1);
        }
    }
}
  

型号:

public class Data {

    private int id;
    private String title,capa;

    public Data(int id, String title, String capa) {
        this.id = id;
        this.title = title;
        this.capa = capa;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getCapa() {
        return capa;
    }

    public void setCapa(String capa) {
        this.capa = capa;
    }
}

1 个答案:

答案 0 :(得分:3)

更改适配器的此覆盖方法:

@Override
public int getItemCount() {
    return Integer.MAX_VALUE;
}

并使用此方法通过位置获取模型对象:

private Data getItem(int position) {
    return my_data.get(position % my_data.size());
}

由于您使用的是RecyclerView,因此不会创建新对象,并且列表中会重复填充您的商品。