Hi guys I have a case here. I have an activity inside which there is a recycler view. The recycler view contains cardview as items. There are two buttons on the activity i.e. delete and cancel.
Here what I want is that on long click of cardview item of recycler view the delete and cancel button should appear. Also, I should be able to proforma delete by clicking the delete button (i.e. remove the item from recycle view) while cancel button will just remove the selection from the cardview.
What is the approach should I follow. I can implement onLongClick listener inside adapter class of recycler view but how to make button visible.
Please help.
CodePudding user response:
Try this approach in Adapter onBindViewHolder
listview.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
new AlertDialog.Builder(context)
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
list.remove(position);
adapter.notifyDataSetChanged();
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton("cancel", null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
return true;
}
});
CodePudding user response:
We can use Interface to communicate the click listener, between the activity and view holder.
Interface
interface IRecyclerViewListener {
void onItemClick(int position);
}
Activity
class RecyclerActivty implements IRecyclerViewListener {
//This is user defined method...
public void setADapter() {
RecyclerAdapter adapter = new RecyclerAdapter(this);
recyclerview.setAdapter(adapter);
}
public void onItemClick(int position) {
//Handle the button visibility here...
}
}
RecyclerAdapter
class RecyclerAdapter extends RecyclerView.Adapter<ViewHolder> {
private IRecyclerViewListener iRecyclerViewListener = null;
public RecyclerAdapter (IRecyclerViewListener iRecyclerViewListener) {
this.iRecyclerViewListener = iRecyclerViewListener;
}
}
Now the interface object has been passed to adapter, from their we can pass to viewholder same way via constructor. In View holder inside the view click listener write iRecyclerViewListener.onItemClick(getAdapterPosition());. This way we can communicate from adapter to activity.