我有一个arraylist CastArrayList,其中在onResponseVolley方法中添加了数据,然后从那里检查CastArrayList的大小是否大于7,另一个arraylist subCastArrayList复制了CastArraylist从位置0到7,并将其发送到RecyclerView,但在RecyclerView中没有任何视图。我想如果CastArrayList大小大于7 SubCastArrayList应该复制前7个元素,否则复制整个CastArrayList,然后将SubCastArrayList发送到adapter

ArrayList<Cast> castArrayList;
ArrayList<Cast> subCastArrayList;
castArrayList = new ArrayList<>();
subCastArrayList = new ArrayList<>();

castDetailAdapter = new
CastDetailAdapter(MovieView.this,castArrayList,subCastArrayList);

RecyclerView.LayoutManager mLayoutManager = new
StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.HORIZONTAL);

recycler_view.setLayoutManager(mLayoutManager);
recycler_view.setItemAnimator(new DefaultItemAnimator());
recycler_view.setAdapter(castDetailAdapter);

StringRequest stringRequest1 = new StringRequest(Request.Method.GET, url,
    new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            int i;
            for (i=0;i<movieDetailFull.getCredits().getCast().size();i++) {
                Cast cast = new Cast();

                cast.setName(movieDetailFull.getCredits().getCast().get(i).getName());

                cast.setId(movieDetailFull.getCredits().getCast().get(i).getId());

                castArrayList.add(i,cast);
                castDetailAdapter.notifyDataSetChanged();
            }
        }

        if (castArrayList.size() > 7) {

            subCastArrayList  = new ArrayList<Cast>
            (castArrayList.subList(0,6));
            castDetailAdapter.notifyDataSetChanged();
        }
        else {
            subCastArrayList = new ArrayList<Cast>(castArrayList);
            castDetailAdapter.notifyDataSetChanged();
        }

最佳答案

您正在通过创建新的arraylist来更改subCastArrayList列表的引用,这意味着subCastArrayList和适配器中的list是对不同列表的两个不同引用

所以只添加元素

subCastArrayList.clear();
// ^^^ clear the list instead of creating new one inside if or else
if (castArrayList.size() > 7)
{
    //subCastArrayList.addAll(castArrayList.subList(0,6));
    subCastArrayList.addAll(castArrayList.subList(0,7));
    // upper range is exclusive so use              ^
}else{
    subCastArrayList.addAll(castArrayList);
}
    castDetailAdapter.notifyDataSetChanged();
   // move notify outside , avoid redundant statements

08-05 14:25