Reputation: 1005
So i;m try to implement a method in which when a button is clicked a new line or item is added to the recyclerview. I've read up a good bit about this and i just cant get my head around it. Any help would be hugely appreciated!
Here my adapter I believe this is where you write most of the code to add items to a recyclerview:
public class DazAdapter extends RecyclerView.Adapter<DazAdapter.MyViewHolder> {
List<Information> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
public DazAdapter(Context context, List<Information> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
public void addData(Information newModelData, int position) {
data.add(position, newModelData);
notifyItemInserted(position);
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Information current = data.get(position);
holder.title.setText(current.title);
}
@Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.listText);
}
}
}
Upvotes: 2
Views: 13009
Reputation: 509
did you try calling notifyDataSetChanged() instead of notifyItemInserted on your addData method?
In my case, i used it to load my data from a Loader, but i think it should work when you add a single item.
public void onLoadFinished(Loader<List<Data>> loader, List<Data> data) {
this.mAdapter.setDatas(data);
this.mAdapter.notifyDataSetChanged();
}
Upvotes: 1