Last item removed from RecyclerView but still visible on Layout - android

I have recyclerview on my Fragment.When I am deleting the last item from Recyclerview it gets deleted but it is visible on Layout. I need to manually refresh the Fragment then it is gone. This happens only for deleting the last item otherwise delete the item from RecyclerView works fine.
This is code for calling Delete method using interface from AdapterClass
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView name;
private TextView number;
private TextView people;
private ImageView deleteReservation;
public ViewHolder(View itemView, final OnEntryClickListener listener) {
super(itemView);
name=(TextView)itemView.findViewById(R.id.name);
number=(TextView) itemView.findViewById(R.id.number);
people=(TextView)itemView.findViewById(R.id.people);
deleteReservation=(ImageView)itemView.findViewById(R.id.delete);
editReservation=(ImageView)itemView.findViewById(R.id.editReservation);
deleteReservation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener!=null) {
int position = originalList.indexOf(filter.get(getAdapterPosition()));
if (position != RecyclerView.NO_POSITION) {
listener.deleteReservation(position);
}
}
}
});
This is code for deleting item from RecyclerView
#Override
public void deleteReservation(final int position) {
removePeople = current.get(position).getNoOfPeople();
removeId = current.get(position).getReserveid();
removeTime = current.get(position).getFullTime();
AlertDialog.Builder confirm = new AlertDialog.Builder(getActivity());
confirm.setTitle("Confirmation");
confirm.setMessage("Are you sure to cancel reservation ?");
confirm.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
removeFromReservation();
removeItem(position);
}
});
This is method to delete item.
public void removeItem(int position) {
current.remove(position);
adapter.notifyItemRemoved(position);
//adapter.notifyItemRangeChanged(position, current.size());
adapter.notifyDataSetChanged();
if(current.size()==0){
current.clear();
getData();
}
}

try this function hope it works for you
public void removeItemAt(int position) {
current.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, current.size());
}

Pass ItemView along with the position parameter in order to Invisible it. I have written my connect hopefully it will work for you!
listener.deleteReservation(position,itemView);
public void deleteReservation(final int position , View itemView){
.
.
.
public void onClick(DialogInterface dialog, int which) {
removeFromReservation();
removeItem(position,itemView); // there pass again
}
}
Make ItemView invisible or Gone in this method...
public void removeItem(int position,itemView) {
current.remove(position);
adapter.notifyItemRemoved(position);
//adapter.notifyItemRangeChanged(position, current.size());
itemView.setVisibility(View.GONE);
adapter.notifyDataSetChanged();
if(current.size()==0){
current.clear();
getData();
}
}

Related

Having challenge in RecyclerView item's onClickListener

I have an item list which are placed under a RecyclerView. On any item, there a quantity(add or subtract). When add is selected, the quantity should increase one.
But when i clicked on '+' for the first time, the value of quantity is setting to 1 and soon after resetting to 0, but when i click on second time the value is becoming '1'. Similarly when i click on next time the value is setting to 2 and after a fraction of second it is still getting to 1 and i click on another time the value is becoming 2. Why by first click is not getting recognized? Can someone please help me here?
public class ItemListAdapter extends RecyclerView.Adapter<ItemListAdapter.ItemViewHolder>{
private Context mContext;
private List<Items> itemsList;
private OnItemListListner onClick;
public ItemListAdapter(Context mContext,List<Items> itemsList)
{
this.mContext=mContext;
this.itemsList=itemsList;
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(mContext);
View view=inflater.inflate(R.layout.item_details_layout,null);
return new ItemListAdapter.ItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ItemViewHolder holder, final int position) {
Items items=itemsList.get(position);
Log.d("onBindViewHolder",items.getItemName());
holder.itemNameTV.setText(items.getItemName());
String strItemPrice=mContext.getResources().getString(R.string.Rs)+" "+String.valueOf(items.getItemPrice());
holder.itemPriceTV.setText(strItemPrice);
holder.itemDescTV.setText(items.getItemDescription());
Glide.with(mContext).load(items.getItemImagePath()).into(holder.imageView);
holder.itemAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int intCurrentQuantity=Integer.valueOf(holder.itemQuantity.getText().toString());
intCurrentQuantity+=1;
Log.d("myQuantity",String.valueOf(intCurrentQuantity));
holder.itemQuantity.setText(String.valueOf(intCurrentQuantity));
notifyItemChanged(holder.getAdapterPosition());
}
});
holder.itemNameTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick.onItemListClick(position);
}
});
holder.itemPriceTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick.onItemListClick(position);
}
});
holder.itemDescTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick.onItemListClick(position);
}
});
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick.onItemListClick(position);
}
});
}
#Override
public int getItemCount() {
return itemsList.size();
}
public void SetOnClick(OnItemListListner onClick)
{
this.onClick=onClick;
}
class ItemViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView itemNameTV,itemPriceTV,itemDescTV,itemQuantity,itemSubtract,itemAdd;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
imageView=itemView.findViewById(R.id.itemImageView);
itemNameTV=itemView.findViewById(R.id.itemNameTextView);
itemPriceTV=itemView.findViewById(R.id.itemPriceTextView);
itemDescTV=itemView.findViewById(R.id.itemDescritionTextView);
itemQuantity=itemView.findViewById(R.id.itemQuantity);
itemSubtract=itemView.findViewById(R.id.subtractQuantity);
itemAdd=itemView.findViewById(R.id.addQuantity);
}
}
public interface OnItemListListner{
void onItemListClick(int position);
}
}
you should have the quantity property in Item model class and have to follow the code I added below.
holder.itemAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = item[getAdapterPosition()].quantity;
quantity = quantity +1;
item[getAdapterPosition()].setQuantity(quantity);
notifyItemChanged(getAdapterPosition());
}
});
Thanks.I am sure this will work for you.
Reviewd your code and then after i'm just agreed with Harsh's Answer
there is a two way to set your adapter. most commonly used Model for storing and retriving data.
You need to create a one model class and and set data first into the model then after get data from model and set into your adapter / notify your adapter.
You need to create one variable in model class like below snippet:
public class Item {
String mQty = "";
public String getmQty() {
return mQty;
}
public void setmQty(String mQty) {
this.mQty = mQty;
}
}
Helpful Answer: Click Me
Recycler view recycles the views on scroll and resets its content, so you have to persist the quantity qty variable. You can do it by two ways
Store quantity inside your Items model.
Persist quantity in seperate HashMap as item.getId() as key and qty as value.
then get and set from the model object or hashmap.
Check updated code
holder.itemAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int intCurrentQuantity=Integer.valueOf(holder.itemQuantity.getText().toString());
++intCurrentQuantity; //use this
Log.d("myQuantity",String.valueOf(intCurrentQuantity));
holder.itemQuantity.setText(String.valueOf(intCurrentQuantity));
notifyItemChanged(holder.getAdapterPosition());
}
});

Is this a wrong way to implement a RecyclerView in Android?

Im trying to implement a RecyclerView in my app. This is my Adapter class:
public class AdapterItemsList extends RecyclerView.Adapter<AdapterItemsList.ViewHolderItems>
{
private ArrayList<CItem> items;
public AdapterItemsList(ArrayList<CItem> items)
{
this.items = items;
}
#NonNull
#Override
public ViewHolderItems onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_counter, null, false);
return new ViewHolderItems(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolderItems holder, final int position)
{
holder.asignarDatos(items.get(holder.getAdapterPosition()));
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
//deleteSelectedItem() method gonna be here
Toast.makeText(view.getContext(), String.valueOf(holder.getAdapterPosition())
, Toast.LENGTH_SHORT).show();
return false;
}
});
holder.counterAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer auxInteger = Integer.parseInt(holder.itemNumber.getText().toString());
auxInteger += 1;
holder.itemNumber.setText(auxInteger.toString());
items.get(holder.getAdapterPosition()).setObjectNumber(Integer.parseInt(holder.itemNumber.getText().toString()));
}
});
holder.counterSubtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer auxInteger = Integer.parseInt(holder.itemNumber.getText().toString());
if (auxInteger > 0)
{
auxInteger -= 1;
holder.itemNumber.setText(auxInteger.toString());
items.get(holder.getAdapterPosition()).setObjectNumber(Integer.parseInt(holder.itemNumber.getText().toString()));
}
}
});
}
#Override
public int getItemCount()
{
return items.size();
}
public class ViewHolderItems extends RecyclerView.ViewHolder
{
TextView itemName;
TextView itemNumber;
Button counterAdd;
Button counterSubtract;
public ViewHolderItems(View itemView)
{
super(itemView);
itemName = (TextView) itemView.findViewById(R.id.textViewItemCounterName);
itemNumber = (TextView) itemView.findViewById(R.id.textViewItemCounterNumber);
counterAdd = (Button) itemView.findViewById(R.id.buttonItemCounterAdd);
counterSubtract = (Button) itemView.findViewById(R.id.buttonItemCounterSubtract);
}
public void asignarDatos(CItem item)
{
itemName.setText(item.getObjectName());
itemNumber.setText(item.getObjectNumber().toString());
}
}
}
The code that "creates" the adapter:
private void CreateAdapter() {
recyclerViewItems.setAdapter(null);
items.clear();
//I dont post the code, but this just gets data from a SQLite database and populate "items".
LoadClientsList();
final AdapterItemsList adapter = new AdapterItemsList(items);
recyclerViewItems.setAdapter(adapter);
}
As you can see, I never use "implements View.OnLongClickListener" or something like that, but I just set the OnClickListener inside onBindViewHolder. Now there is a "Toast" inside (which appears just fine when I test the app), but later on, there should be my "delete item" dialog, that gonna give the user the change to Accept or Cancel (an usual dialog). If the user press "accept" then I gonna remove the item from the list.
I gonna admit, Im not an Android or Java Ninja, so I know there are horrendous mistakes probably. But the thing is, the app is working by now (the Toast appears correctlywhen I long-press an item), but the fact that I never use "implements", while I see everyone does it in StackOverflow questions related to RecyclerViews and Adapters, make me think Im making (several) serious mistakes.
I could admit since Im not a master at Java fundamentals (some years working with COBOL already that I remember almost NULL of OOP), I don't see where my mistakes are, but still, any help will be much appreciated.
Thanks in regard!
UPDATE:
Ok I was changing my code and now its like follows:
public class AdapterItemsList extends
RecyclerView.Adapter<AdapterItemsList.ViewHolderItems> implements
View.OnClickListener {
private ArrayList<CItem> items;
/* Added this */
private View.OnClickListener listener;
public AdapterItemsList(ArrayList<CItem> items)
{
this.items = items;
}
#NonNull
#Override
public ViewHolderItems onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_counter, null, false);
/* Added this */
view.setOnClickListener(this);
return new ViewHolderItems(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolderItems holder, final int position)
{
holder.asignarDatos(items.get(holder.getAdapterPosition()));
holder.counterAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer auxInteger = Integer.parseInt(holder.itemNumber.getText().toString());
auxInteger += 1;
holder.itemNumber.setText(auxInteger.toString());
items.get(holder.getAdapterPosition()).setObjectNumber(Integer.parseInt(holder.itemNumber.getText().toString()));
}
});
holder.counterSubtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer auxInteger = Integer.parseInt(holder.itemNumber.getText().toString());
if (auxInteger > 0)
{
auxInteger -= 1;
holder.itemNumber.setText(auxInteger.toString());
items.get(holder.getAdapterPosition()).setObjectNumber(Integer.parseInt(holder.itemNumber.getText().toString()));
}
}
});
}
#Override
public int getItemCount() { [...] }
/* Added this */
public void setOnClickListener(View.OnClickListener listener)
{
this.listener = listener;
}
/* Added this */
#Override
public void onClick(View view) {
if (listener != null)
{
listener.onClick(view);
}
}
public class ViewHolderItems extends RecyclerView.ViewHolder { [...] } }
Code where I create the adapter:
private void CreateAdapter() {
recyclerViewItems.setAdapter(null);
items.clear();
LoadClientsList();
final AdapterItemsList adapter = new AdapterItemsList(items);
/* Added this */
adapter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), String.valueOf(recyclerViewItems.getChildAdapterPosition(view)), Toast.LENGTH_SHORT).show();
}
});
recyclerViewItems.setAdapter(adapter);
}
The "recyclerViewItems.getChildAdapterPosition(view)" finally solves my problem (didn't mentioned before, but it was the reason why I put the "setOnClick..." inside the onBindViewHolder method, just because I needed the position of the pressed item and I couldnt figure out how on earth to access it).
So now I set the listener when I create the adapter instead of when Binding the View holder, which I guess it's better.
Still, I didnt change the "holder.counterAdd.setOnClickListener" and "holder.counterSubtract.setOnClickListener" lines, since I think they must be inside the onBindViewHolder method, but I guess Im still wrong on that.
I disagree with most of the comments on your question, and I think that the way you've written your adapter is pretty good. It's not perfect, but there is nothing wrong with manually setting a View.OnClickListener to some (or many) views inside your ViewHolder. In fact, this is the Google-recommended way of doing things!
I would make some changes, however. The first would be to move the declaration of your click listeners into the onCreateViewHolder() method (by putting them inside the ViewHolder's constructor). The second would be to add checks for NO_POSITION to make sure you handle the case where an item has been removed from your adapter but the layout hasn't been recalculated yet.
Here is what I'd recommend:
public ViewHolderItems(View itemView)
{
super(itemView);
itemName = (TextView) itemView.findViewById(R.id.textViewItemCounterName);
itemNumber = (TextView) itemView.findViewById(R.id.textViewItemCounterNumber);
counterAdd = (Button) itemView.findViewById(R.id.buttonItemCounterAdd);
counterSubtract = (Button) itemView.findViewById(R.id.buttonItemCounterSubtract);
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
deleteItem();
return true;
}
});
counterAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemAdd();
}
});
counterSubtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemSubtract();
}
});
}
private void deleteItem() {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
items.remove(position);
adapter.notifyItemRemoved(position);
}
}
private void itemAdd() {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
CItem item = items.get(position);
item.setObjectNumber(item.getObjectNumber() + 1);
adapter.notifyItemChanged(position);
}
}
private void itemSubtract() {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
CItem item = items.get(position);
if (item.getObjectNumber() > 0) {
item.setObjectNumber(item.getObjectNumber() - 1);
adapter.notifyItemChanged(position);
}
}
}
And then your onBindViewHolder() is extremely simple:
#Override
public void onBindViewHolder(#NonNull ViewHolderItems holder, int position)
{
holder.asignarDatos(items.get(position));
}
So, let's talk about what I'm doing here.
First, I pushed all of the listener setup into the constructor of your ViewHolder. This means that the listeners are all assigned exactly once. In order to make that still function in a world where ViewHolders are recycled and attached to different items, we have to use getAdapterPosition() to make sure that we're always interacting with the correct item in your list.
We have to check for NO_POSITION because RecyclerView layout operations are asynchronous: when you delete an item from the list, there is a gap where the item doesn't exist in your adapter any more but still is displayed on screen. In this gap, the user might tap a button! In these cases, we just ignore the user input.
I also changed how you update the values of your items, and how you display those updates. Rather than getting the text and parsing it and then re-setting it, I always go through the adapter. Remember that the goal of your RecyclerView implementation is to be able to display any element in your list correctly. The best way to do this is to update the element in your data set, and then notify the RecyclerView that that element has changed, and let onBindViewHolder() take care of the required updates.

Disabling a RecyclerView

I'm facing the next problem.
I have a RecyclerView with the Adapter, the items, etc.
What I need is: Select an item in the recycler, change the color of that item, and then I have to disable the rest of the other items. It's like a RadioButton list.
I select one and disable the others. If I select again the same item, enable all the list.
I already have the onClick Button listener. I need to know if I have to reload again de list, If I have to loop and disable item by item, etc.
Thanks
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<Human> humans;
private HumanClick selectedHuman;
#Inject
public MyAdapter() {
}
public void init(List<Human> humanList, SelectedHumanClick humanClick){
this.humans = humanList;
this.humanClick = humanClick;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_Human, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
final Human human = Humans.get(position);
holder.bind(Humans.get(position));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedHumanClick.onSelectedHumanClick(Human);
}
});
}
#Override
public int getItemCount() {
return humans != null ? Humans.size() : 0;
}
public final class MyViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.text_view_human_name)
TextView textView;
#BindView(R.id.image_view_profile)
ImageView imageViewProf;
#BindView(R.id.image_view_radio_btn)
ImageView imageViewRB;
private boolean isChecked = false;
public MyViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bind(final Human Human) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
humanClick.onSelectedHumanClick(Human);
}
});
textView.setText(human.getName());
}
public void changeRBImage() {
if(!isChecked){
isChecked = true;
imageViewRB.setBackground(ContextCompat.getDrawable(imageViewRB.getContext(), R.drawable.selected));
}
else{
isChecked = false;
imageViewRB.setBackground(ContextCompat.getDrawable(imageViewRB.getContext(), R.drawable.not_selected));
}
}
}
My Recycler is defined inside a fragment here:
public class HumansFragment implenets HumanClick{
#BindView(R.id.recycler_humans)
RecyclerView humansRecyclerView;
#Inject
MyAdapter myAdapter;
.
.
.
public void loadHumans(List<Human> humans) {
myAdapter.init(Humans, this);
humansRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
humansRecyclerView.setAdapter(myAdapter);
}
#Override
public void humansClick(Human human) {
//TODO
}
}
I'm thinking in something like this, using setOnItemClickListener and check the position of the item clicked. The position is the index of the item clicked check the last event and new, if both are equal change color, if not dont do anything like disabling.
private ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
textView = (TextView)view.findViewById(android.R.id.text1);
}
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "position = " + getLayoutPosition(), Toast.LENGTH_SHORT).show();
//go through each item if you have few items within recycler view
if(getLayoutPosition()==0){
//Do whatever you want here
}else if(getLayoutPosition()==1){
//Do whatever you want here
}else if(getLayoutPosition()==2){
}else if(getLayoutPosition()==3){
}else if(getLayoutPosition()==4){
}else if(getLayoutPosition()==5){
}
//or you can use For loop if you have long list of items. Use its length or size of the list as
for(int i = 0; i<exampleList.size(); i++){
}
}
}
Or something smaller
RecyclerView recyclerView = findViewById(R.id.recycler);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(context, recyclerView ,new
RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
// do whatever
}
#Override public void onLongItemClick(View view, int position) {
// do whatever
}
})
);

Recyclerview pass the data to next item upon deletion of one item

The title seems confusing because I cannot explain this properly using text.
I'll try my best to explain my problem.
Currently I have items in my recyclerview :
Each item contains a delete button that will remove the item in the recyclerview.
Lets assume that I have 5 items in the list:
what I want to attain is when the user deletes
Item 2
the information/data from item 3 will be transferred to Item 2,
the data from item 4 will be transferred to item 3 and
the data from item 5 will be transferred to item 4
and lastly the item 5 will be deleted.
I currently have no code for this but I'm trying my best to construct it.
Here is my adapter code, it might help:
public class CreditCard_PostPayAdapter extends RecyclerView.Adapter<CreditCard_PostPayAdapter.MyViewHolder> {
private static String TAGedittext = "";
//private final AccountHistoryTransactionActivity homeActivity;
private Context mContext;
private ArrayList<Integer> mHeaderText;
CreditCard_PostPayAdapter adapter;
public CreditCard_PostPayAdapter(Context mContext, ArrayList<Integer> mHeaderTextList ) {
this.mContext = mContext;
this.mHeaderText = mHeaderTextList;
}
#Override
public CreditCard_PostPayAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.creditcard_postpay_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final CreditCard_PostPayAdapter.MyViewHolder holder, int position) {
final int pos = position + 1;
final int mPosition = position;
if (mHeaderText.size() == 1) {
holder.mDeleteButton.setVisibility(View.GONE);
} else {
holder.mDeleteButton.setVisibility(View.VISIBLE); }
holder.mDeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mHeaderText.remove(mPosition);
ArrayList<Integer> temp = new ArrayList<Integer>();
for (int i = 0 ; mHeaderText.size() - 1 >= i ; i++) {
temp.add(i);
Log.d("Counter++",""+i);
}
holder.mMerchantName.setText("");
holder.mTransactionAmountEditText.setText("");
holder.mTransactionDateEditText.setText("");
holder.mPostingDateEditText.setText("");
mHeaderText.clear();
mHeaderText.addAll(temp);
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return mHeaderText.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView mHeaderTitle
public ImageView mArrowHeader;
public ImageButton mDeleteButton;
public TextInputEditText mTransactionDateEditText,
mPostingDateEditText,
mTransactionAmountEditText;
public MyViewHolder(View view) {
super(view);
this.mHeaderTitle = (TextView) view.findViewById(R.id.header_title);
this.mDeleteButton = view.findViewById(R.id.mDeleteButton);
this.mMerchantName = view.findViewById(R.id.mMerchantNameTextView);
this.mTransactionDateEditText = view.findViewById(R.id.Transaction_date);
this.mPostingDateEditText = view.findViewById(R.id.posting_date);
this.mTransactionAmountEditText = view.findViewById(R.id.Transaction_amount);
}
}
}
My current delete button function is to:
Delete the item(n) and recount all of the remaining item.
Replace your onBindViewHolder method and try,
#Override
public void onBindViewHolder(final CreditCard_PostPayAdapter.MyViewHolder holder, int position) {
holder.mDeleteButton.setTag(position);
holder.mDeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int clickedPos = (int) view.getTag();
mHeaderText.remove(clickedPos);
notifyItemRemoved(position);
}
});
}
If you want to delete the 2nd element. delete the element and remaining will be taken care by recyclerAdapter to remove the row and align the data.
inside your onClickListener, remove the data from ArrayList and the call notifyItemRemoved()
write your onClick inside ViewHolder class
onClick(View view){
mHeaderText.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
}
i hope this will help you..
you an delete the item in list and refresh your adapter by just doing this in your onClick:
holder.mDeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mHeaderText.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mHeaderText.size());
}
});

remove selected item from recyclerView on click delete image icon

I want remove selected item from recyclerView list.
In my list I have delete image icon each row and I want delete item when clicked delete image icon. How can do it?
My adapter code this is see my code how can do it:
thank you
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ItemViewHolder>{
private Context context;
private List<Items> items=new ArrayList<>();
public ListAdapter(Context context){
this.context=context;
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater=LayoutInflater.from(context);
View view=layoutInflater.inflate(R.layout.item,parent,false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
holder.bindItem(items.get(position));
}
#Override
public int getItemCount() {
return items.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder{
private TextView titleTextView;
private ImageView editIcon;
private ImageView deleteIcon;
public ItemViewHolder(View itemView) {
super(itemView);
titleTextView =itemView.findViewById(R.id.item_title);
editIcon=itemView.findViewById(R.id.item_edit);
deleteIcon=itemView.findViewById(R.id.item_delete);
}
public void bindItem(Items item){
titleTextView.setText(item.getTitle());
}
public void removeItem(int position){
items.remove(position);
notifyItemRemoved(position);
}
}
public void addItem(Items item){
items.add(item);
notifyItemInserted(items.size()-1);
}
}
Try below code
public ItemViewHolder(View itemView) {
super(itemView);
titleTextView =itemView.findViewById(R.id.item_title);
editIcon=itemView.findViewById(R.id.item_edit);
deleteIcon=itemView.findViewById(R.id.item_delete);
// put this code
deleteIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeItem(getAdapterPosition())
}
});
}
The answer above does the job but it is always better to use interface callback for easier implementation and code modularity. Below is the code that i like to write for removing the list item from activity. In this method you dont have to alter much code of adapter class and in case you want to do more complicated such as: remove the list element only when element from firebase database is removed, this method does this job perfectly.
here is a code snippet
new DeclinedClickListener() {
#Override
public void declinedClick(int position, View v) {
fbDB.getReference("news_requests").child(articles.get(position).getNewsID()).removeValue(new DatabaseReference.CompletionListener() {
#Override
public void onComplete(#Nullable DatabaseError databaseError, #NonNull DatabaseReference databaseReference) {
articles.remove(position);
if(article_req_rv.getAdapter()!=null) {
article_req_rv.getAdapter().notifyDataSetChanged();
}
}
});
you make a interface for it
public interface DeclinedClickListener {
void declinedClick(int position, View v);
}
Use this inteface in recyclerview
holder.declined_btx.setOnClickListener(l->{
declinedClickListener.declinedClick(position,l);
});

Categories

Resources