动态添加项目,但没有给出我想要的输出,静态数据工作正常,但没有动态数据。视图有时会重复,有时会创建空视图。
片段服务电话:
public void getDataFromServer() {
try {
RequestParams params = new RequestParams();
String url = ApplicationConstants.GET_ITEMS;
if (networkClient!= null)
networkClient.getData(url, params, new ItemsDataListener());
} catch (Exception e) {
e.printStackTrace();
}
}
class ItemsDataListener extends ResponseHandler{
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] byteResponse) {
try {
String response = new String(byteResponse);
if (response != null && !response.isEmpty()) {
Model model=new Gson().fromJson(response,Model.class);
mAdapter.addItem(model, 2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, byte[] byteResponse) {
}
}
这是我的适配器中的方法:
public class ItemCardAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context = null;
private ArrayList<Model> itemList;
public ItemCardAdapter(Context context) {
super();
this.context = context;
this.activity = (Activity) context;
itemList= new ArrayList<>();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, final int viewType) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.single_item_view, viewGroup, false);
ItemCardHolder itemCardHolder = new ItemCardHolder(v);
return itemCardHolder ;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int i) {
(holder instanceof ItemCardHolder) {
Model model=itemList.get(i)
((ItemCardHolder) holder).populateData(model);
}
}
@Override
public int getItemCount() {
return itemList.size();
}
@Override
public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
super.onViewDetachedFromWindow(holder);
((ItemCardHolder) holder).cardview.clearAnimation();
}
public void addItem(Model newItem, int position) {
itemlist.add(position, newItem);
this.notifyItemInserted(position);
this.notifyItemChanged(position);
}
public void clearData() {
itemList.clear();
this.notifyDataSetChanged();
}
}
答案 0 :(得分:0)
你这里做错了
mAdapter.addItem(model, 2);
即使没有数据,也会尝试在2位置添加项目。尝试从适配器获取项目数,然后尝试添加项目。