在Android中向下滚动RecyclerView

时间:2016-09-24 14:31:07

标签: java android json android-recyclerview

我想在Android应用程序中从Flickr下载图片并在我的RecyclerView(GridLayoutManager)中显示它们。这是我用页面获取它的代码(默认页面= 1)

public List<GalleryItem> fetchItems(Integer page){
    if (page==null) page=1;
    List<GalleryItem> items=new ArrayList<>();
    try {
        String url = Uri.parse("https://api.flickr.com/services/rest/")
                .buildUpon()
                .appendQueryParameter("method", "flickr.photos.getRecent")
                .appendQueryParameter("api_key", API_KEY)
                .appendQueryParameter("format", "json")
                .appendQueryParameter("nojsoncallback", "1")
                .appendQueryParameter("extras", "url_s")
                .appendQueryParameter("page",page.toString())
                .build().toString();
        String jsonString = getUrlString(url);
        Log.i(TAG, "Received JSON: " + jsonString);

        JSONObject jsonBody = new JSONObject(jsonString);
        parseItems(items,jsonBody);
}
    catch (JSONException jse){
        Log.e(TAG,"Failed to parse JSON",jse);
    }
    catch (IOException ioe){
        Log.e(TAG,"Failed to fetch items",ioe);
    }
    return items;
}

当我收到这些项目时,我将它们添加到recyclerviews适配器项目,并观察我是否在这种情况下没有达到结束以获取新数据(使用来自How to implement endless list with RecyclerView?的帮助)

private RecyclerView mPhotoRecyclerView;
private List<GalleryItem> mItems=new ArrayList<>();

GridLayoutManager mGridLayoutManager;
int pastVisibleItems, visibleItemCount, totalItemCount,currentpage=1;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v=inflater.inflate(R.layout.fragment_photo_gallery,container,false);

    mPhotoRecyclerView=(RecyclerView)v.findViewById(R.id.fragment_photo_gallery_recycler_view);
    mGridLayoutManager=new GridLayoutManager(getActivity(),3);
    mPhotoRecyclerView.setLayoutManager(mGridLayoutManager);
    mPhotoRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (dy>0) {
                visibleItemCount = mGridLayoutManager.getChildCount();
                totalItemCount = mGridLayoutManager.getItemCount();
                pastVisibleItems = mGridLayoutManager.findFirstVisibleItemPosition();
              //  ppastVisibleItems = mGridLayoutManager.findLastVisibleItemPosition();


                if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
                    currentpage++;
                    new FetchItemsTask().execute(new Integer[]{currentpage});
                }
            }
        }
    });
    setAdapter();
    return v;
}

private void setAdapter(){
    if(isAdded()){
        mPhotoRecyclerView.setAdapter(new PhotoAdapter(mItems));
    }
}

我的AsyncTask实现

private class FetchItemsTask extends AsyncTask<Integer,Void,List<GalleryItem>>{

        @Override
        protected List<GalleryItem> doInBackground(Integer... voids) {
//            try{
//
//                String result=new FlickrFetchr().getUrlString("https://www.bignerdranch.com");
//                Log.i(TAG,"Fetched contents of URL: "+result);
//            }
//            catch (IOException ioe){
//                Log.e(TAG,"Failed to fetch URL: "+ioe.getMessage(),ioe);
//            }
            return new FlickrFetchr().fetchItems(currentpage);
        }

        @Override
        protected void onPostExecute(List<GalleryItem> items) {
            mItems.addAll(items);
            setAdapter();
        }
    }

我认为问题在于

 if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
                currentpage++;
                new FetchItemsTask().execute(new Integer[]{currentpage});
            }

每次我花费越来越多的时间滚动查看。第一次滚动:totalItemCount = 100,它工作正常。在下一个滚动,pastVisibleItems等于0,totalItemCount = 200(flickr给出页面100),因此需要花费越来越多的时间来重新下载新的图片。我试着用

if ((visibleItemCount + pastVisibleItems+(currentpage-1)*100) >= totalItemCount) {
                    currentpage++;
                    new FetchItemsTask().execute(new Integer[]{currentpage});
                }

然后回收者视图不断显示我的第一页(。我该如何正确实现它?

以下是我的适配器和ViewHolder代码

private class PhotoHolder extends RecyclerView.ViewHolder{
    private TextView mTitleTextView;
    public PhotoHolder(View itemView) {
        super(itemView);
        mTitleTextView=(TextView)itemView;
    }
    public void bindGalleryItem(GalleryItem item){
        mTitleTextView.setText(item.toString());
    }
}

private class PhotoAdapter extends RecyclerView.Adapter<PhotoHolder>{
    private List<GalleryItem> mGalleryItems;

    public PhotoAdapter(List<GalleryItem> galleryItems) {
        mGalleryItems=galleryItems;
    }

    @Override
    public PhotoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        TextView textView=new TextView(getActivity());
        return new PhotoHolder(textView);
    }

    @Override
    public void onBindViewHolder(PhotoHolder holder, int position) {
        holder.bindGalleryItem(mGalleryItems.get(position));
    }

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

1 个答案:

答案 0 :(得分:0)

我找到了答案,将pastVisibleItems设置为零的原因是因为在

中生成了新的适配器实例
private void setAdapter(){
if(isAdded()){
    mPhotoRecyclerView.setAdapter(new PhotoAdapter(mItems));
}

}

我把它改成了

private void setAdapter(){
    if(isAdded()){

        if (mPhotoRecyclerView.getAdapter()==null)
            mPhotoRecyclerView.setAdapter(new PhotoAdapter(mItems));
        else
            mPhotoRecyclerView.getAdapter().notifyDataSetChanged();
    }
}

现在一切都很棒!感谢您的关注)