Multi selection in RecyclerView - android

I have list of data with CheckBox. I need to check or uncheck my Check Box from my RecyclerView. When I am trying this more than one check box is selected.
public class AttendanceAdapter extends RecyclerView.Adapter<AttendanceAdapter.MyStudentsViewHolder>{
private LayoutInflater inflater;
private Context contexts;
List<studinformation> data= Collections.emptyList();
public AttendanceAdapter(Context context,List<studinformation> data){
inflater=LayoutInflater.from(context);
this.data=data;
this.contexts=context;
}
#Override
public MyStudentsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= inflater.inflate(R.layout.customrow_students,parent,false);
MyStudentsViewHolder holder=new MyStudentsViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyStudentsViewHolder holder, int position) {
studinformation current=data.get(position);
holder.studentid.setText(current.studID);
holder.studentname.setText(current.studName);
holder.studentid.setSelected(true);
}
#Override
public int getItemCount() {
return data.size();
}
class MyStudentsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CheckBox studentid;
TextView studentname;
public MyStudentsViewHolder(View itemView) {
super(itemView);
studentid= (CheckBox) itemView.findViewById(R.id.ChkSid);
studentname= (TextView) itemView.findViewById(R.id.textName);
studentid.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(contexts, "Item Clicked At" + getPosition(), Toast.LENGTH_SHORT).show();
if(getPosition()==0) {
// Intent intent = new Intent(contexts, SubActivity.class);
// contexts.startActivity(intent);
}
}
}
}

RecyclerView will reuse the view.so when you return after scrolling it will reset the data it's happening because you are not setting your checkbox selected or not.
In your StudInformation model class create a property isSelected
public class StudInformation
{
private boolean isSelected=false;
public void setSelected(boolean param)
{
this.isSelected=param;
}
public boolean isSelected()
{
return this.isSelected;
}
}
Inside onClick
#Override
public void onClick(View v) {
data.get(getLayoutPosition()).setSelected(studentid.isChecked());
}
In onBindViewHolder
#Override
public void onBindViewHolder(MyStudentsViewHolder holder, int position) {
.....
studinformation current=data.get(position);
holder.studentid.setSelected(current.isSelected());
}
Cross reference link

you have to use setTag() method to get position of each checkbox.
Use this code instead of holder.studentid.setSelected(true); and remove studentid.setOnClickListener(this);
holder.studentid.setChecked(data.get(position).isSelected());
holder.studentid.setTag(data.get(position));
holder.studentid.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
String id = String.valueOf(cb.getTag());
Toast.makeText(
v.getContext(),
"Clicked on Checkbox: " + id, Toast.LENGTH_LONG).show();
}
});

Related

Only two checkbox can select user , how to achieve this?

This is screenshot
I want only select two checkboxes from the listing of checkboxes........................................................................................................................................................................................................................................................................................
Below is my code
public class OfferItemsAdapter extends RecyclerView.Adapter<OfferItemsAdapter.ViewHolder> {
private ArrayList<TaskListModel.Option> mDataset;
String strFreeItem;
OfferItemsAdapter(ArrayList<TaskListModel.Option> reviwsLists, String strFreeItem) {
mDataset = reviwsLists;
this.strFreeItem = strFreeItem;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.addon_list_cart_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.cbProduct.setText(mDataset.get(position).getItemName());
holder.tvProductPrice.setVisibility(View.GONE);
if (strFreeItem.equalsIgnoreCase("1")) {
if (mDataset.get(position).isChecked()) {
holder.cbProduct.setChecked(true);
selectedItems.add(mDataset.get(position).getItemID());
} else {
holder.cbProduct.setChecked(false);
selectedItems.remove(mDataset.get(position).getItemID());
}
}
holder.cbProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (strFreeItem.equalsIgnoreCase("1")) {
if (selectedItems.size() == 1 && selectedItems.contains(mDataset.get(position).getItemID())) {
mDataset.get(position).setChecked(false);
} else {
mDataset.get(position).setChecked(true);
}
}
notifyDataSetChanged();
Log.e("selectedItems.toString()............",""+selectedItems.toString());
}
});
}
#Override
public int getItemCount() {
return mDataset == null ? 0 : mDataset.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public View mainView;
TextView tvProductPrice;
CheckBox cbProduct;
public ViewHolder(View v) {
super(v);
mainView = v;
tvProductPrice = v.findViewById(R.id.tvProductPrice);
cbProduct = v.findViewById(R.id.cbProduct);
}
}
}
First of all, you should use setOnCheckedChangeListener instead of setOnClickListener.
And use setOnCheckedChangeListener and check selectedItems size everytime user check the checkbox like the following.
holder.cbProduct.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if (isChecked){
if(selectedItems.size()<2){
selectedItems.add(mDataset.get(position).getItemID());
mDataset.get(position).setChecked(true);
}else{
holder.cbProduct.setChecked(false);
// here you can show a toast or log that user can't select more than two items.
}
}else{
selectedItems.remove(mDataset.get(position).getItemID());
mDataset.get(position).setChecked(false);
}
}
}
);

RecyclerView get View by position

I have a RecyclerView and each CardView contains a TextView and an ImageView. Whenever I click an item, I want to set the image visibility to VISIBLE and to set the previous clicked item image's visibility to INVISIBLE.
This is my Adapter class :
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder>{
private Context context;
private List<Category> lista;
private LayoutInflater layoutInflater;
private IncomeCategoryActivity activity;
private static final int CATEGORY_REQUEST=6;
private static final int ITEM_EDIT=1;
private static final int ITEM_DELETE=2;
private static final int EDIT_REQUEST=7;
private int current_pos=-1;
public CategoryAdapter(List<Category> lista, Context context, IncomeCategoryActivity activity) {
this.context = context;
this.lista = lista;
this.activity=activity;
layoutInflater=LayoutInflater.from(context);
}
#Override
public CategoryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=layoutInflater.inflate(R.layout.category_layout, parent, false);
ViewHolder viewHolder=new ViewHolder(view, activity);
return viewHolder;
}
#Override
public void onBindViewHolder(CategoryAdapter.ViewHolder holder, int position) {
holder.imageView.setImageURI(lista.get(position).getUri());
holder.textView.setText(lista.get(position).getCategory());
holder.position = position;
holder.category=lista.get(position);
if(holder.category.isChecked()==true){
holder.imageViewCheck.setVisibility(View.VISIBLE);
current_pos=position;
} else {
holder.imageViewCheck.setVisibility(View.INVISIBLE);
}
}
#Override
public int getItemCount() {
return lista.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener{
public ImageView imageView;
public TextView textView;
public ImageView imageViewCheck;
public int position;
public Category category;
public IncomeCategoryActivity activity;
public ViewHolder(View itemView, IncomeCategoryActivity activity) {
super(itemView);
this.activity=activity;
imageView=itemView.findViewById(R.id.customCategoryImageView);
textView=itemView.findViewById(R.id.customCategoryTextView);
imageViewCheck=itemView.findViewById(R.id.customCheckImageView);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
String aux=textView.getText().toString();
if(aux=="CATEGORIE NOUĂ"){
Intent intent=new Intent(context, CustomIncomeActivity.class);
activity.startActivityForResult(intent, CATEGORY_REQUEST);
}
else{
imageViewCheck.setVisibility(View.VISIBLE);
int pozitie_check=getLayoutPosition();
Intent intent=new Intent(context, AddIncomeActivity.class);
intent.putExtra("categorie_venit", aux);
intent.putExtra("position_check", pozitie_check);
activity.setResult(Activity.RESULT_OK, intent);
activity.finish();
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Selectează acțiunea");
MenuItem edit=menu.add(0, ITEM_EDIT, 0, "Modifică");
MenuItem delete=menu.add(0, ITEM_DELETE, 0, "Șterge");
edit.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
int position=getLayoutPosition();
if (item.getGroupId() == 0) {
if(item.getItemId()==ITEM_EDIT){
Category category=lista.get(position);
Intent intent=new Intent(activity, CustomIncomeActivity.class);
intent.putExtra("edit_icon", category.getUri());
intent.putExtra("edit_category", category.getCategory());
intent.putExtra("list_position", position);
activity.startActivityForResult(intent, EDIT_REQUEST);
}
else if(item.getItemId()==ITEM_DELETE){
lista.remove(position);
notifyDataSetChanged();
}
}
return true;
}
At this moment, whenever I click an item, there are two images VISIBLE on the RecyclerView: the clicked item's image and the previous clicked item's image. I think I need to get the previous View by its position and to manually set the visibility to INVISIBLE.
recycleView.getChildCount() and recycleView_parent.getChildAt() only gives the Adapter items which is shows only screen .
that means if your list has 200 items and the only 5 items shows on screen so we can find only 5 item with the help of recycleView
i am using one simple trick to solve the issue.
You can define Hashmap which hold your holder objects
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
ArrayList<Model> dataList;
Context context;
HashMap<Integer,ViewHolder> holderlist;
public MyAdapter(ArrayList<Model> dataList, Context context) {
this.context = context;
this.dataList = dataList;
holderlist = new HashMap<>();
}
And after that to save the holder in Hashmap
public void onBindViewHolder(final ViewHolder holder, final int position) {
if(!holderlist.containsKey(position)){
holderlist.put(position,holder);
}
Create a method in Adapter.
public MyListAdapter.ViewHolder getViewByPosition(int position) {
return holderlist.get(position);
}
Call this method from your Activity or whenever you want.
for (int i = 0; i < datalList.size(); i++) {
MyAdapter.ViewHolder holder = ((MyAdapter)recycleView.getAdapter()).getViewByPosition(i);
View view = holder.itemView;
TextView tv = view.findViewById(R.id.tv);
}
I have created the demo you can refer it and implement for single selection
recyclerView.setAdapter(new RecyclerView.Adapter() {
int selected_position = -1;
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new RecyclerView.ViewHolder(LayoutInflater.from(parent.getContext()).inflate(
R.layout.row_color_list,parent,false)) {
#Override
public String toString() {
return super.toString();
}
};
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
ImageView imageView = holder.itemView.findViewById(R.id.image);
if(selected_position == position){
imageView.setVisibility(View.VISIBLE);
}else {
imageView.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selected_position != holder.getAdapterPosition()){
selected_position = holder.getAdapterPosition();
notifyDataSetChanged();
}
}
});
}
#Override
public int getItemCount() {
return 20;
}
});
You can do as following:
1) Declare a global variable:
private int selectedPos = -100; // Put any irrelevant number you want
2) Set selected position onClick() :
#Override
public void onClick(View v) {
selectedPos = getAdapterPosition();
}
3) Check selected postion and assign visibility inside onBindViewHolder():
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
if(position == selectedPos){
holder.imageViewCheck.setVisibility(View.VISIBLE);
} else {
holder.imageViewCheck.setVisibility(View.INVISIBLE);
}
}
Try this code..
add this code into adapter class for handling click event..
OnItemClick onItemClick;
public void setOnItemClick(OnItemClick onItemClick) {
this.onItemClick = onItemClick;
}
public interface OnItemClick {
void getPosition(String data); //pass any data to shared it.
}
after bind method..
#Override
public void onBindViewHolder(final ItemViewHolder holder, final int position) {
// below code handle click event on recycler view item.
final String str=mStringList.get(position); // here your boject
if(holder.category.isChecked()==true){
holder.imageViewCheck.setVisibility(View.VISIBLE);
current_pos=position;
} else {
holder.imageViewCheck.setVisibility(View.INVISIBLE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClick.getPosition(str); // pass your data.
}
});
}
after bind adapter into recycler view it means adapter not null then called below code..
adpater.setOnItemClick(new RecyclerViewAdpater.OnItemClick() {
#Override
public void getPosition(String data) {
// hear update your value for check into if condition.
data="sdfsdf";
adpater.notifyDataSetChanged();
}
});
and also read comments and also try to make custon class and access that object value and update after click it..
this code only how to handle click event into recycler view.

How to get image from recyclerview position clicked data and set it into another imageview?

I have an app which contains recyclerview with imageview and text.When I click on item based on position that is imageview i want image of that image view and set it to another Imageview.To do this I have made interface and implements its method in Activity but need to know that how do i do that
Adapter code:
public interface OnItemClicked {
void onItemClicked(int position);
}
public AvatarListAdapter(Context context, int[] arrayList) {
this.mContext = context;
this.dataModel = arrayList;
}
#Override
public AvatarListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.avatar_items, parent, false);
return new AvatarListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(AvatarListAdapter.ViewHolder holder, final int position) {
holder.mAvatarImage.setImageResource(dataModel[position]);
holder.mAvatarImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick.onItemClicked(position);
}
});
}
public void setOnClick(OnItemClicked onClick) {
this.onClick = onClick;
}
#Override
public int getItemCount() {
return dataModel.length;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private CircleImageView mAvatarImage;
public ViewHolder(View itemView) {
super(itemView);
mAvatarImage = itemView.findViewById(R.id.img_avatar);
}
}
}
Activity code:
private void initializeActions() {
int numberOfColumns = 3;
mAvatarImages.setLayoutManager(new GridLayoutManager(AvatarProfileImage.this, numberOfColumns));
mAdapter = new AvatarListAdapter(AvatarProfileImage.this, avatar);
mAvatarImages.setAdapter(mAdapter);
mAdapter.setOnClick(this);
}
#Override
public void onItemClicked(int position) {
String pos = "You clicked at position " + position;
Toast.makeText(getApplicationContext(), "You clicked position" + pos, Toast.LENGTH_LONG).show();
mAvatarImages.setBackgroundResource(avatar[position]);
}
You can get data by position on OnClick().As you are using local drawable for image resource, One way to do is Modify your viewHolder as follows.This is just a one way you can also use ViewTag.
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private Circle mAvatarImage;
public ViewHolder(View itemView) {
super(itemView);
mAvatarImage = itemView.findViewById(R.id.img_avatar);
mAvatarImage.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int postion =getAdapterPosition();
int image =arrayList[postion];
// Use this image to forward
}
}
Remove OnClick from onBindViewHolder.
Implement RecycleView onClick() method and get specified data while onclick position.have look
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private Circle mAvatarImage;
public ViewHolder(View itemView) {
super(itemView);
mAvatarImage = itemView.findViewById(R.id.img_avatar);
mAvatarImage.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position=arrayList[getAdapterPosition()];
String imagepath = arraylist.get(position).getImagePath
//you can use imagepath anywhere you want either be put in bundle or intent call
}
}
Adapter code should look like this
private final OnItemClickListener listenerOnItemClick;
public interface OnItemClickListener {
void onItemClick(int position); }
public AvatarListAdapter(Context context, int[] arrayList, OnItemClickListener listenerOnItemClick) {
this.mContext = context;
this.dataModel = arrayList;
this.listenerOnItemClick=listenerOnItemClick;
}
#Override
public AvatarListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.avatar_items, parent, false);
return new AvatarListAdapter.ViewHolder(view); }
#Override
public void onBindViewHolder(AvatarListAdapter.ViewHolder holder, final int position) {
holder.mAvatarImage.setImageResource(dataModel[position]);
holder.mAvatarImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick.onItemClicked(position);
}
}); }
public void setOnClick(OnItemClicked onClick) {
this.onClick = onClick; }
#Override
public int getItemCount() {
return dataModel.length; }
public class ViewHolder extends RecyclerView.ViewHolder {
private CircleImageView mAvatarImage;
public ViewHolder(View itemView) {
super(itemView);
mAvatarImage = itemView.findViewById(R.id.img_avatar);
} }
Activity Code
AvatarListAdapter.OnItemClickListener onItemClickListener = new AvatarListAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
//change your Image here
String pos = "You clicked at position " + position;
Toast.makeText(getApplicationContext(), "You clicked position" + pos, Toast.LENGTH_LONG).show();
mAvatarImages.setBackgroundResource(avatar[position]);
}
};
private void initializeActions() {
int numberOfColumns = 3;
mAvatarImages.setLayoutManager(new GridLayoutManager(AvatarProfileImage.this, numberOfColumns));
mAdapter = new AvatarListAdapter(AvatarProfileImage.this, avatar,onItemClickListener );
mAvatarImages.setAdapter(mAdapter);
mAdapter.setOnClick(this);
}

On Scrolling Check Boxes are getting Unchecked or Vice versa in a RecyclerView

I have a check box in RecyclerView Adapter's View Item.
When scrolling, some check boxes are getting checked and some are getting unchecked.
I have taken help from this and this
But I am unable to find the exact solution to this.
Here is my code
public class AllContactsAdapter extends RecyclerView.Adapter<AllContactsAdapter.ViewHolder> {
private Context context;
private ArrayList<PhoneContactsModel> listOfContacts = new ArrayList<>();
PhoneContactsModel phoneContactsModel;
private ArrayList<PhoneContactsModel> copyOfListOfContacts = new ArrayList<>();
public AllContactsAdapter(Context context, ArrayList<PhoneContactsModel> listOfContacts) {
this.context = context;
this.listOfContacts = listOfContacts;
// copyOfListOfContacts.addAll(listOfContacts);
}
#Override
public AllContactsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.
adapter_load_allusers_contacts_listitem, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final AllContactsAdapter.ViewHolder holder, final int position) {
Log.d("tag", "adapter========3");
phoneContactsModel = listOfContacts.get(position);
holder.name.setText(phoneContactsModel.getContactName());
holder.phoneNumber.setText(phoneContactsModel.getContactNumber());
holder.checkBox.setSelected(phoneContactsModel.isChecked());
holder.contactLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.checkBox.isChecked()) {
phoneContactsModel.setChecked(false);
holder.checkBox.setChecked(false);
copyOfListOfContacts.remove(listOfContacts.get(position));
} else {
phoneContactsModel.setChecked(true);
holder.checkBox.setChecked(true);
copyOfListOfContacts.add(listOfContacts.get(position));
}
}
});
}
#Override
public int getItemCount() {
return listOfContacts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView name, phoneNumber;
private CheckBox checkBox;
private LinearLayout contactLayout;
public ViewHolder(View view) {
super(view);
name = view.findViewById(R.id.contactNameId);
phoneNumber = view.findViewById(R.id.contactNumberId);
checkBox = view.findViewById(R.id.checkBoxId);
contactLayout = view.findViewById(R.id.contactLayoutId);
}
}
}
For example, I have checked 1,2,3 items in list. When I scrolled down and come up , then 13 is checked and 2 is unchecked along with other some items.Please help me.
Any solution is appreciated.
A simple way arround is do not use OnCheckedChangeListener just set OnClickListener on Check box . Move checkBox onclick inside ViewHolder class.
public class ViewHolder1 extends RecyclerView.ViewHolder implements View.OnClickListener {
CheckBox checkBox;
public ViewHolder1(View itemView) {
super(itemView);
checkBox = (TextView) itemView.findViewById(R.id.checkBox);
checkBox.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(getAdapterPosition()!=-1) {
phoneContactsModel.get(getAdapterPosition()).setChecked(!phoneContactsModel.get(getAdapterPosition()).isChecked());
notifyItemChanged(getAdapterPosition());
}
}
}
And
public void onBindViewHolder(final AllContactsAdapter.ViewHolder holder, final int position) {
holder.checkBox.setChecked(phoneContactsModel.isChecked());
}
notify your adapter.
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
phoneContactsModel.setChecked(b);
//notifyItemChanged(position);(if you want to notify change in single item)
//or
//notifyDataSetChanged();(if you want to notify change in all)
}
});
no need to use this line of code twice
holder.checkBox.setSelected(phoneContactsModel.isChecked());
//this section seems buggy i assume you want to add the item to the list when ever the check box is checked and remove it from the list when ever the check box is unchecked.
holder.contactLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (phoneContactsModel.isChecked()) {
holder.checkBox.setSelected(false);
copyOfListOfContacts.remove(listOfContacts.get(position));
} else {
holder.checkBox.setSelected(true);
copyOfListOfContacts.add(listOfContacts.get(position));
}
}
}
);
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final PhoneContactsModel phoneContactsModel = listOfContacts.get(position);
holder.name.setText(phoneContactsModel.getContactName());
holder.phoneNumber.setText(phoneContactsModel.getContactNumber());
holder.checkBox.setChecked(/* gets value from the modal */ phoneContactsModel.isChecked());
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean value) {
if (compoundButton.isPressed()) {
holder.checkBox.setChecked(value);
// set the value into the modal.
phoneContactsModel.setChecked(value);
if (value) {
copyOfListOfContacts.remove(phoneContactsModel);
} else {
copyOfListOfContacts.add(phoneContactsModel);
}
}
}
});
}
Change your onBindViewHolder method like this. There won't be any unnecessary checks.

Removing item from RecyclerView

I am having trouble removing items from RecyclerView. When I click on delete, the item is removed from RecyclerView, but comes back when I open the app again. I'm hoping it is just a minor issue that someone here can point out or direct me to what area to troubleshoot. The removeItem(String item) in bold is what I think is the issue. You can't see it in this post, but it is "not used".
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private List<Grocery> mListData;
private SQLGroceryHelper helper;
RecyclerViewAdapter adapter;
//Adapter's Constructor//
public RecyclerViewAdapter(List<Grocery> mDataList) {
this.mListData = mDataList;
}
//Provide a reference to the views for each contact item//
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView rowItem;
ImageButton purchasedButton;
ImageButton deleteButton;
LinearLayout linearLayout;
public MyViewHolder(View itemView) {
super(itemView);
linearLayout = (LinearLayout) itemView.findViewById(R.id.recycler_row);
rowItem = (TextView) itemView.findViewById(R.id.item_field1);
purchasedButton = (ImageButton) itemView.findViewById(R.id.item_purchased);
deleteButton = (ImageButton) itemView.findViewById(R.id.delete_item);
}
}
//Inflate the view based on the viewtype provided//
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//Create a new view by inflating the row item xml//
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row, parent, false);
//Set the view to the ViewHolder//
MyViewHolder holder = new MyViewHolder(row);
return holder;
}
//Display data at the specified position//
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.rowItem.setText(mListData.get(position).getTextItem());
holder.purchasedButton.setOnClickListener(new View.OnClickListener() {
//Ignore this click for now//
#Override
public void onClick(View v) {
removeItem(position);
}
});
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeItem(position);
}
});
}
public void **removeItem**(String item) {
int position = mListData.indexOf(item);
if (position != -1) {
mListData.remove(item);
notifyItemRemoved(position);
}
}
public void removeItem(int position) {
mListData.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
if (mListData == null) {
return 0;
}
return mListData.size();
}
}
You are removing the data from local object, mListData I guess the original data object remains intact. Remove the data item from the original data object as well
Declare a interface
public interface AdapterCommunication{
void removeStringItem(int position);
}
then in your adapter
private AdapterCommunication mListener;
public void setOnClickListener(AdapterCommunication listener){
mListener = listener;
}
Then from your activity where you initialize the adapter
RecyclerViewAdapter adapter = new RecyclerViewAdapter(list);
adapter.setOnClickListener(new AdapterCommunication{
public void removeStringItem(int position){
list.remove(position);
adapter.notifyDataSetChanged();
}
});
In your adaper,
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.remove(position);
}
});

Categories

Resources