2017-10-20 74 views
1

我發現下面的代碼做一些事情,當我到達一個GridView的末尾:無限呼叫「onScroll」時,網格視圖伸手可及結束

GridView gridview = (YMAnimatedGridview) v.findViewById(R.id.my_gridview); 
    gridview.setAdapter(adapter); 
    final View footerView = mainView 
      .findViewById(R.id.my_grid_footer_view); 
    gridview.setOnScrollListener(new GridView.OnScrollListener() { 

    @Override 
    public void onScroll(AbsListView view, int firstVisibleItem, 
      int visibleItemCount, int totalItemCount) { 

      if (firstVisibleItem + visibleItemCount == totalItemCount) { 

       // last item in grid is on the screen, show footer: 
       fetchMoreItems(); 

      } 
     } 

    @Override 
    public void onScrollStateChanged(AbsListView view, int scrollState) { 
    } 

的事情是,當我到達gridView的結尾,這個方法被連續調用。

private void fetchMoreItems() { 
    Log.i(LOG_TAG, "Reached the end of grid view"); //for debbug purposes 
    Integer lastIndex = thumbnails.length; //This is a Bitmap array with the data I'm alredy showing 
    Cursor cursor = getData(); 
    thumbnails = concat(thumbnails, new Bitmap[30]); 
    Integer lastIndexToRun = Math.min(30, cursor.getCount() - lastIndex); 
    for(int j = 0; j < lastIndexToRun; j++) { 
     Integer i = j + lastIndex; 
     cursor.moveToPosition(i); 
     thumbnails[i] = getThumbnail(i); 
    } 
    adapter.notifyDataSetChanged(); //This is the adapter used to fill the gridview 
    cursor.close(); 
} 

我覺得我的錯誤應該是在fetchMoreItems()方法,但因爲它是利用GridView的我的第一次,我不知道

回答

0

你需要避免多次調用該方法,像這樣:

private int beforeLastItem; 

@Override 
public void onScroll(AbsListView view, int firstVisibleItem, 
        int visibleItemCount, int totalItemCount) { 
    final int lastItem = firstVisibleItem + visibleItemCount; 
    if (lastItem == totalItemCount) { 
     // last item in grid is on the screen, show footer: 
     if (beforeLastItem != lastItem){ //to avoid multiple calls for the last item 
      fetchMoreItems(); 
      beforeLastItem = lastItem; 
     } 
    } else { 
     beforeLastItem = lastItem; 
    } 
} 
0

您可以使用一個布爾值,以防止多個調用是這樣的:

private final boolean isFetching = false; 
    GridView gridview = (YMAnimatedGridview) v.findViewById(R.id.my_gridview); 
    gridview.setAdapter(adapter); 
    final View footerView = mainView 
      .findViewById(R.id.my_grid_footer_view); 
    gridview.setOnScrollListener(new GridView.OnScrollListener() { 

     @Override 
     public void onScroll(AbsListView view, int firstVisibleItem, 
          int visibleItemCount, int totalItemCount) { 

      if (firstVisibleItem + visibleItemCount == totalItemCount && !isFetching) { 
       isFetching = true; 
       // last item in grid is on the screen, show footer: 
       fetchMoreItems(); 

      }else{ 
       if(isFetching){ 
        isFetching = false; 
       } 
      } 
     } 

     @Override 
     public void onScrollStateChanged(AbsListView view, int scrollState) { 
     } 

您可以在獲取完成後將isFetching設置爲false。