Android RecyclerView Item Addition and Removal
Problem
This RecyclerView implementation includes a TextView box and a cross button (ImageView). A button outside the RecyclerView is used to toggle the visibility of the cross button. The objetivo is to remove an item from the RecyclerView when the corresponding cross button is clicked.
Solution
Within the ViewHolder class of the adapter:
Example Adapter Code
<code class="java">public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { private ArrayList<String> mDataset; public MyAdapter(ArrayList<String> myDataset) { mDataset = myDataset; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) { // ... holder.mNameTextView.setOnClickListener(this); holder.crossButton.setOnClickListener(this); return holder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { // ... } @Override public void onClick(View view) { if (view.getId() == holder.crossButton.getId()) { removeAt(holder.getAdapterPosition()); } else if (view.getId() == holder.mNameTextView.getId()) { // ... } } public void removeAt(int position) { mDataset.remove(position); notifyItemRemoved(position); notifyItemRangeChanged(position, mDataset.size()); } public static class ViewHolder extends RecyclerView.ViewHolder { TextView mNameTextView; ImageView crossButton; public ViewHolder(View v) { super(v); mNameTextView = (TextView) v.findViewById(R.id.nameTextView); crossButton = (ImageView) v.findViewById(R.id.crossButton); } } }</code>
The above is the detailed content of How to Remove Items from an Android RecyclerView with Cross Buttons?. For more information, please follow other related articles on the PHP Chinese website!