[英]RecyclerView notifyDatasetChanged not working when notifyDatasetchanged in anonymous class method
我正在尋找有關如何刷新適配器而不重新設置RecyclerView適配器的問題的解決方案。 通過這個回答,我已經完成了,但是沒有做任何事情,我做錯了什么。 這是設置recyclerView適配器的代碼。
public class OrderedFoodsFragment extends Fragment
{
private NewInvoice invoice;
private List<InvoiceItem> items= new ArrayList<>();
private OrderedAdapter adapter;
public OrderedFoodsFragment(NewInvoice invoice)
{
this.invoice = invoice;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_ordered_foods, container, false);
initializeComponents(view);
return view;
}
private void initializeComponents(View view)
{
RecyclerView rvOrderedFoods = (RecyclerView) view.findViewById(R.id.rvOrderedFoods);
adapter= new OrderedAdapter(getActivity(), items,R.layout.ordered_layout);
rvOrderedFoods.setAdapter(adapter);
setInvoiceItems();
}
private void setInvoiceItems()
{
IInvoiceApi api= ApiClient.getClientWithAuthorization(App.getContext()).create(IInvoiceApi.class);
Call<List<InvoiceItem>> call= api.getInvoiceItems(invoice.getId());
call.enqueue(new Callback<List<InvoiceItem>>()
{
@Override
public void onResponse(@NonNull Call<List<InvoiceItem>> call, @NonNull Response<List<InvoiceItem>> response)
{
if (response.isSuccessful())
{
//My comment code
//items=response.body();
//adapter= new OrderedAdapter(getActivity(), items,R.layout.ordered_layout);
//noinspection ConstantConditions
items.clear();
//noinspection ConstantConditions
items.addAll(response.body());
adapter.notifyDataSetChanged();
Log.i("InvoiceData", adapter.getItemAtPosition(0).getName());
}
else if (response.code() == 401)
{
new AlertDialog.Builder(getActivity()).setTitle("Session Expire").setMessage("សិទ្ធក្នុងការប្រើកម្មវិធីអស់ពេល").show();
App.promptUnauthorized(getActivity());
}
else
{
items= new ArrayList<>();
}
}
@Override
public void onFailure(@NonNull Call<List<InvoiceItem>> call, @NonNull Throwable t)
{
call.cancel();
}
});
}
}
我正在使用改造2.0來請求我的數據。 和response.body()有我的數據。 但是recyclerview不顯示數據。 但是,如果我將onRespose方法中的適配器重新設置為response.body()作為此方法中的注釋代碼,則它可以工作,但我不希望這樣。 任何解決方案都可以幫助我。
您必須將此新列表設置為適配器。
您可以在適配器中創建setDataSet()方法並在notifydatasetchanged之前調用它
在適配器中添加以下方法
public void setDataSet(List<InvoiceItem> items) {
this.items= items;
}
並在notifydatasetChanged之前調用它,如下所示:
adapter.setDataSet(items);
adapter.notifyDataSetChanged();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.