2016-03-02 41 views
8

我是回收商視圖的新手。我的要求如下: - 我必須調用一個將提供兩個數組的Web服務。一個需要在列表中顯示的數據。爲此,我使用RecyclerView。另一個陣列是狀態,我在微調中顯示。此Web服務分頁。我已添加分頁,它工作正常。 - 當用戶從微調框中選擇一些其他元素時,我必須再次進行Web服務調用,並且應該更改回收者視圖數據。 目前,分頁我做以下的情況下,一旦我從連續頁獲得更多的數據:Android:需要更新從微調框中選擇的項目的回收視圖的建議

mAccountListingsAdapter.notifyItemRangeInserted(mAccountListingsAdapter.getItemCount(), mListings.size() - 1); 

而且,當我改變從微調的數據,我做以下操作:

mListings.clear();//Clear the data set 

mAccountListingsAdapter.notifyDataSetChanged();//Call notify data set changed on recycler view adapter 

getAccountListings();//Fetch new data from the web service and display in recycler view 

但是,建議您不要直接在回收視圖適配器上調用notifyDataSetChanged(),而應該調用特定的notifyXXX方法,以避免出現性能和動畫問題。

因此,我懷疑,如果我正在做的權利,通知微調控制器onItemSelected()回收視圖適配器,或者它應該改變。

P.S.我試過之後在onItemSelected

int size = mListings.size(); 
mListings.clear(); 
mAccountListingsAdapter.notifyItemRangeRemoved(0, size - 1); 

但隨後墜毀,有以下情況除外:

03-02 12:59:41.046: E/AndroidRuntime(4270): java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 4(offset:0).state:5 

回答

4

我覺得notifyItemRangeRemoved是在這裏使用了正確的方法,但你傳遞的第二個參數的值是錯的。根據文檔,第二個參數是從數據集中刪除的項目數量,您傳遞的是最後一項刪除的位置。

enter image description here

所以下面的代碼應該工作正常

int size = mListings.size(); 
mListings.clear(); 
mAccountListingsAdapter.notifyItemRangeRemoved(0, size); 

欲瞭解更多信息請參閱:http://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#notifyItemRangeRemoved(int,%20int)

+0

+1我的錯誤阿布舍克 - 我開始寫我的答案,並在最後發佈之前休息了一下。在我看來,其他人可能在此期間發佈了答案。現在,我會保留爲其提供的其他信息發佈的答案。 – Vikram

+0

@Vikram當然。沒問題。 –

1

首先,爲notifyItemRangeRemoved (int, int)方法定義是:

public final void notifyItemRangeRemoved (int positionStart, int itemCount) 

第二個參數我s爲count,而不是positionEnd。在你的情況下,你通過size - 1作爲第二個參數,當它應該是size本身。

int size = mListings.size(); 
mListings.clear(); 
// should be notifyItemRangeRemoved(0, size) 
mAccountListingsAdapter.notifyItemRangeRemoved(0, size - 1); 

其次,notifyDataSetChanged()時,因爲它觸發的所有可見的觀點重新綁定和重新佈局的皺起了眉頭。在你的情況下,可見項目的數量爲零,我不明白爲什麼notifyDataSetChanged()會降低性能。如果您正在動畫刪除項目,請使用notifyItemRangeRemoved(0, size)。否則,在這裏完全可以使用notifyDataSetChanged()

相關問題