2017-02-22 53 views
1

我需要一些幫助!在RecyclerView中添加日期部分

我已經關注this獲取一些結果的指南。

適配器已建立,recyclerview已初始化,但我遇到問題 顯示正確的數據在列表中。

因此,這裏是我想要做的事:

首先,我存儲臨時列表從API還創建日期的一個數組列表獲取數據。當然,我從數組列表中刪除重複的日期,因爲有一些項目按相同的日期排序。

這裏是一些代碼,以及如何我對日期在部分填充recyclerview和訂貨項目:

// dates - array list of dates(16 February, 20 February..) 
// mEvents - temporarily list with size of 8 items 
// originalList - list of events ordered by date 

for (String date : dates) { 
    originalList.clear(); 
    for (Event event2 : mEvents) { 
     // Checking if item's date from temp. list is equal with 
     // iterated date and adding to original list 
     if (date.equals(event2.getDate())) { 
      originalList.add(event2); 
     } 
    } 

     // Attaching section to adapter with iterated date and array list related to that date 
     EventSection eventSection 
    = new EventSection(R.layout.lst_item_event_header, R.layout.lst_item_event_v2, date, originalList, getActivity()); 
         mSectionedRecyclerViewAdapter.addSection(eventSection); 
} 

這裏的問題是,我得到的每一個日期部分從原來的名單最後2項。我在這裏錯過了什麼?

編輯:

// I need to sort items by these dates into sections 
Dates:: [2017-02-16, 2017-02-17, 2017-02-28, 2017-02-22, 2017-02-20] 

Event date:: 2017-02-16 
Event date:: 2017-02-16 
Event date:: 2017-02-17 
Event date:: 2017-02-17 
Event date:: 2017-02-28 
Event date:: 2017-02-22 
Event date:: 2017-02-20 
Event date:: 2017-02-20 

回答

2

好吧,我終於找到了一個解決方案,藉助於autor庫的例子。所以如果有其他人像我這樣的麻煩,這可能會幫助你:

for (String date : dates) { 
    originalList = getEventsWithDate(date); 

    if (originalList.size() > 0) { 
     mSectionedRecyclerViewAdapter.addSection(new EventSection(date, originalList, getActivity())); 
    } 
} 

private List<Event> getEventsWithDate(String date) { 
    List<Event> events = new ArrayList<>(); 

    for (Event event : mEvents) { 
     if (date.equals(event.getDate())) { 
      events.add(event); 
     } 
    } 

    return events; 
} 
+0

對不起,我無法幫助你,但我很高興你明白了。不要忘記把你的答案設置爲正確的答案,所以其他人可以很容易地發現正確的答案:) –

+0

謝謝雷蒙德! –

1

你有一個嵌套的循環,所以我的猜測是,這個問題是某處在那裏。仔細檢查那裏的情況,如果這是你想要的。

for (String date : dates) { 

    // Clear the list here so you render a new list of dates that equal the 
    // event date with the date of this iteration. 
    originalList.clear(); 
    for (Event event2 : mEvents) {  
     if (date.equals(event2.getDate())) { // Check this condition 
      originalList.add(event2); 
     } 
    } 
    ... 
} 

如果這將是真實的,每次你會最終得到64項。我不知道你的數據是什麼,所以我無法爲你驗證。

可能發生的情況是,通過不清除列表,您每次都將更大更大的列表添加到視圖中。在添加新列表之前清除列表,並且只應呈現所需的列表。

+0

我應該在嵌套循環完成後清除原始列表嗎? –

+0

是的,這很可能。您現在正在渲染完整列表,然後再添加更多並打印整個列表。我會稍微擴展我的答案。 –

+0

現在我收到了每個部分的兩個項目,並且都是相同的。 –