2016-10-14 322 views
1

我有一個列表,任何用戶可以隨時更新。該列表顯示在RecyclerView中。我想實時更新此列表,以便用戶可以獲得更好的用戶體驗,因爲用戶不需要多次執行刷新。現在問題是,我怎樣才能實時更新這個列表?如何實時更新RecyclerView?

+0

取決於:您的數據來自哪裏? –

+1

你可以調用:'yourAdapter.notifyDataSetChanged();' –

+0

數據來自webservice。我必須先更新數據。我將如何實時與webservice進行通信? Hadi Satrio –

回答

3

使用RecyclerView,您可以使用適配器更新單個項目,項目範圍或整個列表

您必須使用RecyclerView適配器的方法,如adapter#notifyItem***adapter#notifyDataSetChanged()(這將更新RecyclerView中的整個項目列表)。

class RVAdapter extends ...{ 
    List<?> itemList; 

public void updateList (List<Object> items) { 
     if (items != null && items.size() > 0) { 
      itemList.clear(); 
      itemList.addAll(items); 
      notifyDataSetChanged(); 
     } 
    } 

} 
+0

但數據來自web服務。我必須先更新數據。我將如何實時與webservice進行通信? –

+0

您必須解析數據並存儲在列表中。因此,您可以將傳遞給RecyclerView的列表與您從webservice獲取的新列表互換。 –

0

您可以調用同一套回收站適配器代碼。 別忘了打電話adapter#notifyDataSetChanged()

0

您可以在適配器內部創建metod來更新數據並刷新您的recyclerview。

class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{ 
    List<Data> data; 
    ... 

public void update(ArrayList<Data> datas){ 
    data.clear(); 
    data.addAll(datas); 
    notifyDataSetChanged(); 
} 
    ... 
} 

只需調用傳遞新數據的update方法即可。而已。