[英]Passing Data to RecyclerView Adapter
我打電話給改造,響應的大小就是我希望作為RecyclerView適配器的主要數據集傳遞的大小。 我可以確認我已成功致電Retrofit。
我很好奇如何將數據集的大小傳遞給MyAdapter類。 下面是我的代碼:
在我的主要活動中:
call.enqueue(new Callback<List<Recipe>>() {
@Override
public void onResponse(Call<List<Recipe>> call, Response<List<Recipe>> response) {
Log.v("TAG", String.valueOf(response.isSuccessful()));
mRecipeListResponse = response.body();
for (Recipe recipe : mRecipeListResponse){
Log.v("ID", recipe.getId().toString());
}
mAdapter.setDataSet(mRecipeListResponse);
mRecipeList.setAdapter(mAdapter);
; }
@Override
public void onFailure(Call<List<Recipe>> call, Throwable t) {
Log.v("TAG", t.getMessage());
}
});
MyAdapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<Recipe> mRecipeDataSet;
public class ViewHolder extends RecyclerView.ViewHolder{
protected CardView mCardView;
protected TextView mTextView;
public ViewHolder(View itemView) {
super(itemView);
mCardView = itemView.findViewById(R.id.recipe_cardview);
mTextView = itemView.findViewById(R.id.id_of_recipe_item);
}
}
@NonNull
@Override
public MyAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_item, parent,false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull MyAdapter.ViewHolder holder, int position) {
String id = mRecipeDataSet.get(position).getId();
holder.mTextView.setText(id);
}
@Override
public int getItemCount() {
return mRecipeDataSet.size();
}
public List<Recipe> setDataSet(List<Recipe> recipeList){
return mRecipeDataSet;
}
public List<Recipe> getmRecipeDataSet() {
return mRecipeDataSet;
}
}
我的猜測是,你開始MyAdapter
與空mRecipeDataSet
。 請嘗試以下代碼。
private List<Recipe> mRecipeDataSet = new ArrayList<Recipe>();
並替換您的代碼
//this is wrong, it doesn't do the right thing as the function name suggests.
public List<Recipe> setDataSet(List<Recipe> recipeList){
return mRecipeDataSet;
}
至
public void setDataSet(List<Recipe> recipeList){
mRecipeDataSet = recipeList;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.