2016-03-29 30 views
0

加載更多數據後,網格視圖返回頂部,我想讓它在加載後繼續從最後一個項目滾動。 我試圖使用onScrollStateChanged,並使其在state == SCROLL_STATE_TOUCH_SCROLL加載,但我面臨同樣的問題。有沒有辦法來防止gridview的適配器的數據更改時滾動到其頂部的位置?

@Override 
    protected void onPostExecute(ArrayList<productDetails> AProducts) { 
     final ArrayList<productDetails> products = AProducts; 
     super.onPostExecute(products); 

     productAdapter = new productAdapter(category.this, productDetailsArr); 
     gridView.setAdapter(productAdapter); 
     productAdapter.notifyDataSetChanged(); 


     if (products != null) { 
      gridView.setOnScrollListener(new AbsListView.OnScrollListener() { 

       @Override 
       public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { 
        if (firstVisibleItem + visibleItemCount >= totalItemCount) { 
         // End has been reached 
         limit = Integer.parseInt(((productDetails) (products.get(products.size() - 1))).getProductID()); 
         // limit = Integer.parseInt(products.get(3).get(products.get(3).size() - 1)); 


         if (flimit != limit) { 
          flimit = limit; //to stop using last element in fatching last products more than one time. 
          if (UtilityClass.isInternetAvailable(getApplicationContext())) { 

                    new getProductsTask().execute(category); 


          } else { 
           Intent internet = new Intent(getBaseContext(), NointernetConnection.class); 
           startActivity(internet); 
           finish(); 

          } 
         } else { 
          Log.d("FLimit", ">>" + "END"); 
         } 

        } else { 
         progressDialog.dismiss(); 
        } 

       } 

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

       } 

      }); 

     } 
    } 

回答

1

首先,你並不需要創建適配器類(productAdapter)在onPostExecute方法每一次的新對象,並設置適配器的GridView每次當數據變化或您的網絡呼叫。這種新的響應滾動gridview到最高位置的原因。相反,您可以在您的適配器類中創建一個setter方法。

ArrayList <productDetails> productDetailsArr; 

public void setProductDetailsArr(ArrayList<productDetails> productDetailsArr) { 
      this.productDetailsArr = productDetailsArr; 
     } 

和onPostExecute方法寫下下面的代碼,以檢查是否adaper爲空或not.If null,則只有你必須創建一個新的instance.Otherwise你只需要提供一個新的數據集並調用notifyDataSetChanged ()。

if(productAdapter == null) 
{ 
    productAdapter = new productAdapter(category.this, productDetailsArr); 
    gridView.setAdapter(productAdapter); 

}else{ 

    productAdapter.setProductDetailsArr(productDetailsArr); 
    productAdapter.notifyDataSetChanged(); 
    } 
+0

謝謝,它適用於我:D –

相關問題