简体   繁体   中英

Add items to a recycler view?

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);

    }
}

}

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM