Access arraylist from a recycleradapter class - android

I want to access an ArrayList from a nonactivity class to a fragment.
#Override
public void onBindViewHolder(final DataObjectHolder holder, final int position)
{
holder.setIsRecyclable(false);
holder.itemid.setText(mDataset.get(position).getItem_id());
holder.itemname.setText(mDataset.get(position).getItem_name());
holder.qty.setText(mDataset.get(position).getQty());
int rt=Integer.parseInt(mDataset.get(position).getRate().substring(0,mDataset.get(position).getRate().length() - 3));
holder.rate.setText(formatter.format(rt)+".00");
ItemDetails listItem = filterList.get(position);
holder.itemname.setText(listItem.getItem_name());
holder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
holder.qty.setText(String.valueOf(++qt));
mDataset.get(position).setQty(String.valueOf(qt));
finalDataset.add(new ItemDetails(ItemFragment.getInstance().cat_id,String.valueOf(holder.itemid.getText()),String.valueOf(holder.itemname.getText()),String.valueOf(holder.rate.getText()),String.valueOf(holder.qty.getText())));
}
});
holder.minus.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(qt==0)
{
holder.qty.setText(String.valueOf(0));
}
else
{
holder.qty.setText(String.valueOf(--qt));
}
mDataset.get(position).setQty(String.valueOf(qt));
finalDataset.add(new ItemDetails(ItemFragment.getInstance().cat_id,String.valueOf(holder.itemid.getText()),String.valueOf(holder.itemname.getText()),String.valueOf(holder.rate.getText()),String.valueOf(holder.qty.getText())));
}
});
}
finalDataset is the mentioned ArrayList. I added the values to the ArrayList inside the onBindViewHolder method in recycleradapter class. And I want to access it in another fragment.

Create method to return List in adapter class,
public List<ItemDetails> getDataset() {
return finalDataset;
}
In fragment class access it using,
List<ItemDetails> finalDataset = adapter.getDataset();

Related

Recyclerview not refreshing after removing an item

My Recycler view is not updating after an item is removed.
This recyclerView is inside a fragment.
I have tried every method and nothing works.
Adapter declaration in fragment class
notificationsTabAdapter = new NotificationsTabAdapter(getContext(), R.id.notificationsRecyclerView,
notificationItemsList, cListner);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(notificationsTabAdapter);
RecyclerViewAdapter:
public class NotificationsTabAdapter extends RecyclerView.Adapter<NotificationsTabAdapter.NotificationItemHolder> {
Boolean debug = false;
public static final String NOTIFICATION_ADAPTER = "NotificationAdapter";
private ArrayList<NotificationItemm> notificationItems;
private int layoutResID;
private int notificationposition;
private Context myContext;
public onNotificationItemClickListner mListner;
public interface onNotificationItemClickListner {
void onNotificationItemDelete(int position);
}
public NotificationsTabAdapter(Context context, int resource, ArrayList<NotificationItemm> notificationList,
onNotificationItemClickListner listner) {
myContext = context;
layoutResID = resource;
notificationItems = notificationList;
notificationposition = 0;
this.mListner = listner;
}
#NonNull
#Override
public NotificationItemHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.notifications_tab_item, viewGroup, false);
NotificationsTabAdapter.NotificationItemHolder evh = new NotificationsTabAdapter.NotificationItemHolder(view, mListner);
return evh;
}
#Override
public void onBindViewHolder(#NonNull final NotificationItemHolder notificationItemHolder, final int position) {
final NotificationItemm currentItem = notificationItems.get(position);
notificationItemHolder.mNotificationTextView.setText(currentItem.getNotification_name());
notificationItemHolder.mNotificationURL = currentItem.getNotification_link();
notificationItemHolder.mNotificationDate = currentItem.getNotification_date();
notificationItemHolder.mNotificationRT = currentItem.getNotification_rT();
notificationItemHolder.mNotificaionHolderLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
//to delete the notification
notificationItemHolder.imageDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteNotification(currentItem);
mListner.onNotificationItemDelete(position);
}
});
}
#Override
public int getItemCount() {
return notificationItems.size();
}
//Delete from View
public void deleteNotification(NotificationItemm todelete) {
int notificationPosition = notificationItems.indexOf(todelete);
notificationItems.remove(notificationPosition);
notifyItemRemoved(notificationPosition);
notifyItemChanged(notificationPosition);
notifyDataSetChanged();
notifyItemRemoved(notificationPosition);
notifyItemChanged(notificationPosition);
if (notificationItems.isEmpty()) {
}
}
/**
* VIEW HOLDER =================================================================================
**/
public class NotificationItemHolder extends RecyclerView.ViewHolder {
RelativeLayout mNotificaionHolderLayout;
RelativeLayout notificationParentRelative;
ImageView imageDelete;
TextView mNotificationTextView;
String mNotificationURL;
String mNotificationDate;
String mNotificationRT;
public NotificationItemHolder(#NonNull View itemView, onNotificationItemClickListner listner) {
super(itemView);
mNotificationTextView = itemView.findViewById(R.id.NotificationTextView);
mNotificaionHolderLayout = itemView.findViewById(R.id.notification__item_container);
imageDelete = itemView.findViewById(R.id.notification_delete_image);
notificationParentRelative = itemView.findViewById(R.id.rlNotificLayout);
mNotificationRT = null;
mNotificationURL = null;
mNotificationDate = null;
}
}
}
When I debug the project, I can see that the item is actually removing from the ArrayList.But not updating in recycled view.
After deletion, if the recyclerview is scrolled, the deleted item is removed from the recyclerview.But not without scrolling.
Try this.Hope will work for you.
notificationItemHolder.imageDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
notificationItems.remove(position);
notifyDataSetChanged();
}
In your NotificationsTabAdapter make the following changes
NotificationsTabAdapterListener notificationsTabAdapterListener;
public interface NotificationsTabAdapterListener { // create an interface
void onItemsDeleted(int position); // create callback function
}
public NotificationsTabAdapter(Context context, int resource, ArrayList<NotificationItemm> notificationList,
NotificationsTabAdapterListener notificationsTabAdapterListener) {
myContext = context;
layoutResID = resource;
notificationItems = notificationList;
notificationposition = 0;
this.notificationsTabAdapterListener = notificationsTabAdapterListener;
}
notificationItemHolder.imageDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//perform normal remove operation here
notificationItems.remove(position);
notificationsTabAdapterListener.onItemsDeleted(position);
}
});
And Implement NotificationsTabAdapterListener in you fragment and in override method use the following code
#Override
public void onItemsDeleted(final int position) {
notificationsTabAdapter.notifyDataSetChanged();
recyclerView.post(new Runnable() {
#Override
public void run() {
recyclerView.smoothScrollToPosition(position);
}
});
}
Try this to your delete functionality
public void deleteNotification(NotificationItemm todelete) {
notificationItems.remove(todelete);
notifyDataSetChanged();
}
As workaround you can call a method in the FragmentClass, which loads the new list (with item removed) in your adapter. Call this method from your Adapter
public void MethodInFragmentClass(NotificationItemm todelete)
{
/*
... delete item
*/
notificationsTabAdapter = new NotificationsTabAdapter(getContext(), R.id.notificationsRecyclerView,
notificationDeletedItemsList, cListner);
recyclerView.setAdapter(notificationsTabAdapter);
}
Use a callback like this in your adapter :
private ICallback mICallback;
public interface ICallback {
void deleteItem(int position);
}
public SettingRecyclerViewAdapter(SettingMediator settingMediator, ICallback ICallback) {
mICallback = ICallback;
mSettingMediator = settingMediator;
}
And in your faragment notifydatasetchange and update recyclerview like this :
public class YourFragment implements SettingContract.View, SettingRecyclerViewAdapter.ICallback {
.
.
.
#Override
public void deleteItem(int position) {
//delete item from your list here
mSettingRecyclerViewAdapter = new SettingRecyclerViewAdapter(yourList, this);
mRecyclerView.setAdapter(mSettingRecyclerViewAdapter);
mSettingRecyclerViewAdapter.notifyDataSetChanged();
}
}
Try this:
notificationItemHolder.imageDelete.setTag(holder);
notificationItemHolder.imageDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NotificationItemHolder viewholder = (NotificationItemHolder) v.getTag();
notificationItems.remove(viewholder.getAdapterPosition());
notifyDataSetChanged();
}
});
You have to parse the position which is getting from onclick listener in Adapter class to Interface method(onitemClicked())
Then, Implement the interface class to Fragment class and will remove the position which we have on Interface method using [ listname.remove(position)) ]
Eventually, update recyclerview UI using adaptername.notifyDataSetChanged();
Step 1 :create interface class
public interface RecyclerviewItemClickListener {
void onitemClicked(View v, int position);
}
Step 2: pass position to the interface method in adapter class
notificationItemHolder.imageDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteNotification(currentItem);
//use interface method & pass the position of the list to fragment for update UI .
recyclerviewItemClickListener.onitemClicked(v,position);
}
});
step 3 : implement the interface class & method in fragment
#Override
public void onitemClicked(View v, int position) {
Listname.remove(Listname.get(position));
RecyclerviewAdaptername.notifyDataSetChanged();
}

Calling a method from adapter?

I have the following Code:
public static FirestoreRecyclerAdapter adapter;
private void loadList() {
Query query = db.collection("x").document(firebase_user_uid).collection("x");
FirestoreRecyclerOptions<Note> response = new FirestoreRecyclerOptions.Builder<Note>()
.setQuery(query, Note.class)
.build();
adapter = new FirestoreRecyclerAdapter<Note, NoteViewHolder>(response) {
#Override
protected void onBindViewHolder(NoteViewHolder holder, int position, Note model) {
final Note note = notesList.get(position);
holder.title.setText(note.getTitle());
holder.content.setText(note.getContent());
if (note.getNote_image_url() != null) {
Glide.with(MainActivity.this).load(note.getNote_image_url()).into(holder.bg_note_image);
holder.bg_note_image.setVisibility(View.VISIBLE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateNote(note);
}
});
}
#Override
public NoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_note_view, parent, false);
return new NoteViewHolder(view);
}
#Override
public void onError(FirebaseFirestoreException e) {
Log.e("error", e.getMessage());
}
#Override
public int getItemCount() {
return notesList.size();
}
public void removeItem(int position) {
notesList.remove(position);
// notify the item removed by position
// to perform recycler view delete animations
// NOTE: don't call notifyDataSetChanged()
notifyItemRemoved(position);
}
public void restoreItem(Note item, int position) {
notesList.add(position, item);
// notify item added by position
notifyItemInserted(position);
}
};
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
SO, a simple FirestoreRecyclerAdapter. But now I need to call the removeItemMethod inside the adapter. But how to do this?
I tried something like this, but all that didn't work.
public void deleteItem(int position) {
adapter.removeItem(position);
}
I am sitting so long on this Problem. I hope anywhere is a solution to my Problem.
Thanks in advance.
~mb
You get this message because the original FirestoreRecyclerAdapter does not have this method. You should create a separate class extending FirestoreRecyclerAdapter and use it when creating an adapter.
public class MyAdapter extends FirestoreRecyclerAdapter<Note, NoteViewHolder> {
public List<Notes> notesList;
public MyAdapter(List<Notes> notes, FirestoreRecyclerOptions<Note> response) {
super(response);
notesList = notes;
}
#Override
protected void onBindViewHolder(NoteViewHolder holder, int position,
Note model) {
final Note note = notesList.get(position);
holder.title.setText(note.getTitle());
holder.content.setText(note.getContent());
if (note.getNote_image_url() != null) {
Glide.with(MainActivity.this).load(note.getNote_image_url()).into(holder.bg_note_image);
holder.bg_note_image.setVisibility(View.VISIBLE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateNote(note);
}
});
}
#Override
public NoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_note_view, parent, false);
return new NoteViewHolder(view);
}
#Override
public void onError(FirebaseFirestoreException e) {
Log.e("error", e.getMessage());
}
#Override
public int getItemCount() {
return notesList.size();
}
public void removeItem(int position) {
notesList.remove(position);
// notify the item removed by position
// to perform recycler view delete animations
// NOTE: don't call notifyDataSetChanged()
notifyItemRemoved(position);
}
public void restoreItem(Note item, int position) {
notesList.add(position, item);
// notify item added by position
notifyItemInserted(position);
}
}
Something like this. And when you create an adapter :
public static MyAdapter adapter;
And initialising it:
adapter = new MyAdapter(response)
Also, it is not a good idea to keep an adapter static.
Edit: pass the items - notesList - in the constructor.

passing values from recycler adapter to fragment in android

I've a recycler adapter where I've added setOnClickListener for items in adapter. Code is as given below:
#Override
public void onBindViewHolder(final FiltersAdapter.MyViewHolder holder, final int position) {
holder.mOrganizer.setText(filtersList.get(position));
holder.mLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//Log.e("message","ONclick FIlter");
if (holder.mOrganizerCheck.isChecked()){
holder.mOrganizerCheck.setChecked(false);
}else {
holder.mOrganizerCheck.setChecked(true);
int pos = holder.getAdapterPosition();
filtersList.get(pos);
/*Bundle bundle = new Bundle();
bundle.putInt(pos, );*/
Log.d(TAG, "onClick: " +filtersList);
Log.d(TAG, "onClick of position: " +pos);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
And here is fragment code which deals with getting values from adapter to fragment.
private void initView() {
mrvFilterBySender = (RecyclerView) mFilterView.findViewById(R.id.rvFilterBySender);
mFiltersAdapter = new FiltersAdapter(getActivity(), mListOrganizer);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
mrvFilterBySender.setLayoutManager(mLayoutManager);
mrvFilterBySender.setAdapter(mFiltersAdapter);
mFiltersAdapter.notifyDataSetChanged();
mrvFilterBySender.setAdapter(mFiltersAdapter);
mrvFilterBySender.setRecyclerListener(new RecyclerView.RecyclerListener() {
#Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
holder.getAdapterPosition();
}
});
}
I'm trying to pass pos and value having that pos from adapter to fragment. But my code isn't working. How can I fix it?
make interface to handle click event into recyclerview ..
used below code for handling click event.
onItemClickListner onItemClickListner;
public void setOnItemClickListner(RecyclerViewAdpater.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner{
void onClick(String str);//pass your object types.
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
String data=mStringList.get(position); // if you pass object of class then create that class object.
holder.textView.setText(data);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListner.onClick(data);
}
});
}
then after when you bind adapter into RecyclerView call below code..
mRvData.setLayoutManager(new LinearLayoutManager(this));
mRvData.setAdapter(recyclerViewAdpater);
recyclerViewAdpater.notifyDataSetChanged();
recyclerViewAdpater.setOnItemClickListner(new RecyclerViewAdpater.onItemClickListner() {
#Override
public void onClick(String str) {
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
}
});
Create an interface in your adapter
public interface OnItemClickListener {
void onItemClicked(int position, Object object);
}
in your adapter call
Adapter adapter = new Adapter(context, list, new Adapter.OnItemClickListener() {
#Override
public void onItemClicked(int position, Object object) {
// Handle Object of list item here
}
});
on your adapter
private OnItemClickListener onItemClickListener; // Global scope
in constructor call:
this.onItemClickListener = onItemClickListener;
on your item clicked event :
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListener.onItemClicked(position, _list.get(position));
}
});
Please use an interface like below, pass it in the adapter's constructor, and than use it in your activity / Fragment
public MyAdapter(Context context, List<Object> data, MyAdapterListener myAdapterListener) {
this.context = context;
this.data = data;
this.myAdapterListener = myAdapterListener;
}
public interface MyAdapterListener {
void onContainerClick(View view, int position);
}
}
public class ViewHolderItem extends RecyclerView.ViewHolder implements View.OnClickListener {
public LinearLayout container;
public ImageView poster;
public ViewHolderItem(View v) {
super(v);
container = (LinearLayout) v.findViewById(R.id.container);
poster = (ImageView) v.findViewById(R.id.poster);
container =setOnClickListener(this); /// this line must include
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.container) {
if (myAdapterListener != null) {
myAdapterListener.onContainerClick(v,getAdapterPosition());
}
}
}
}
Use it like this in your fragment/Activity
mAdapter = new MyAdapter(getApplicationContext() , data, new MyAdapter.MyAdapterListener() {
#Override
public void onContainerClick(View v, int position) {
Log.d(TAG, "iconTextViewOnClick at position "+position);
}
});
mRecycler.setAdapter(mAdapter);
I thing this is work for you
Add in you adapter
public interface ClickEvent {
void clickEventItem(int position,String value);
}
ClickEvent clickevent;
public void setClickEvent(ClickEvent event) {
this.clickevent = event;
}
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickevent.clickEventItem(position, list.get(position));
}
});
in your fragment set interface
adapter.setClickEvent(your class context);
implement ClickEvent intereface and generate #Override method
#Override
public void clickEventItem(int position,String value) {
//write your code here
}

How do I detect if a button from an activity is clicked while inside a RecyclerView adapter

I have this method in my activity (CreatePhotostoryActivity):
#Override
public void showEditField(Moment oldMoment, final int index){
listRecycler.setVisibility(View.GONE);
editCaption.setVisibility(View.VISIBLE);
saveCancelNavbar.setVisibility(View.VISIBLE);
momentView.setVisibility(View.GONE);
photoStoryNavbar.setVisibility(View.GONE);
header.setVisibility(View.GONE);
Picasso.with(getApplicationContext()).load(oldMoment.photoUri).into(displayPhoto);
imageCaption.setText("");
imageCaption.setText(oldMoment.caption);
backIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeEditMoment();
}
});
saveText.setText("Save Moment");
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateMoment(imageCaption.getText().toString(), index);
Intent i = new Intent(CreatePhotostoryActivity.this, RVAdapter.class);
i.putExtra("isSaved", true);
startActivity(i);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeEditMoment();
Intent i = new Intent(CreatePhotostoryActivity.this, RVAdapter.class);
i.putExtra("isSaved", false);
startActivity(i);
}
});
}
In my RecyclerView adapter, showEditField is called using an interface, and it does work except that I am unable to detect whether saveButton or cancelButton was clicked. This is how it's called in the onBindViewHolder method of my RecyclerView adapter (RVAdapter):
((RecyclerView.ViewHolder) momentViewHolder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mAdapterCallback.showEditField(moments.get(position), position);
Intent intent = ((CreatePhotostoryActivity) mContext).getIntent();
Boolean isSaved = intent.getExtras().getBoolean("isSaved");
if (isSaved) {
holder.momentCaption.setText(moments.get(position).caption);
holder.momentPlaceholder.setVisibility(View.GONE);
holder.momentCaption.setVisibility(View.VISIBLE);
} else {
holder.momentPlaceholder.setVisibility(View.VISIBLE);
holder.momentCaption.setVisibility(View.GONE);
}
notifyDataSetChanged();
});
Do note my attempt of using an intent to find out which button was clicked. It doesn't work. momentCaption remains gone and momentPlaceHolder remains visible even though saveButton was clicked. The app also crashes afterwards.
Edit: I think calling this mAdapterCallback.showEditField(moments.get(position), position); before setting the values of momentCaption and momentPlaceholder is problematic, since showEditField calls other methods (e.g. closeEditMoment() before the intent is retrieved from the adapter.
Create an interface with two methods like saveBtnClick() and cancelBtnClick().
Implement the interface in your Activity.
Implement Click listener for both the buttons in the ViewHolder of your RecyclerView and call the Appropriate methods using Inteface's Object.
//Interface
public interface ManageButtonClicks
{
void saveBtnClick();
}
//Activity
public class MainActivity extends AppCompactActivity implements ManageButtonClicks
{
ManageButtonClicks manageButtonClicks=this;
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
//Do the operations
adapter = new MyAdapter(this,adapterList,manageButtonClicks);
recyclerView.setAdapter(adapter);
}
void saveBtnClick()
{
Toast.makeText(this,"Clicked",Toast.LENGTH_SHORT).show();
}
}
//Adapter Class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
{
ManageButtonClicks manageButtonClicks;
public MyAdapter(Context context, List< ModelClass > data, ManageButtonClicks manageButtonClicks)
{
inflater = LayoutInflater.from(context);
this.mDataList = data;
this.ctx = context;
util = new Util(ctx);
this.manageButtonClicks = manageButtonClicks;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
ViewGroup nonPrimeRow = (ViewGroup) inflater.inflate(R.layout.rowlayout, parent, false);
MyViewHolder_NON_PRIME holderNonPrime = new MyViewHolder_NON_PRIME(nonPrimeRow);
return holderNonPrime;
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position)
{
ModelClass current = mDataList.get(position);
MyViewHolder_NON_PRIME holder_not_prime = (MyViewHolder_NON_PRIME) holder;
holder_not_prime.setdata(current);
}
class MyViewHolder extends RecyclerView.ViewHolder
{
public MyViewHolder(View itemView)
{
super(itemView);
}
}
public class MyViewHolder_NON_PRIME extends MyViewHolder
{
private Button btnSave;
public MyViewHolder_NON_PRIME(View view)
{
super(view);
btnSave = (MonteButton) view.findViewById(R.id.btnSave);
}
public void setdata(final ModelClass current)
{
btnSave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
manageButtonClicks.saveBtnClick();
}
});
}
}
You have a global variable inside recyclerView adapter:
RecyclerViewAdapter {
private boolean isSaveButtonClicked = false;
private boolean isCancelButtonClicked = false;
public void saveButtonClicked(){
isSaveButtonClicked = true;
}}
public void cancelButtonClicked(){
isCancelButtonClicked = true;
}}
When your activity call onclickListeners , you will notice your adapter.
CreatePhotostoryActivity(){
private RecyclerView adapter;
onSaveButtonClicked(){
adapter.saveButtonClicked();
}
onCancelButtonClicked(){
adapter.cancelButtonClicked();
}
}

Select all checkboxes in RecyclerView

How can I select all checkboxes in recyclerView?
I try to do it like this:
in Adapter:
public void selectAll(){
Log.e("onClickSelectAll","yes");
isSelectedAll=true;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
PersonDTO item = dataSet.get(position);
holder.tvName.setText(item.getName());
if (!isSelectedAll) holder.cbSelect.setSelected(false);
else holder.cbSelect.setSelected(true);}
In layout Activity I have a button with onClickListener:
private void onClickSelectAll(View view) {
getSelectPersonsAdapter().selectAll();
}
You made a simple mistake here
if (!isSelectedAll) holder.select_item.setChecked(false);
else holder.select_item.setChecked(true);
change setSelected into setChecked thats it
for both Select All and Unselect All
activty
checkall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkall.isChecked()){
categoryAdapter.selectAll();
}
else {
categoryAdapter.unselectall();
}
}
});
in adapter
public void selectAll(){
isSelectedAll=true;
notifyDataSetChanged();
}
public void unselectall(){
isSelectedAll=false;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(#NonNull final MyviewHolder holder, int position) {
final CategoryListItems list = categoryListItems.get(position);
holder.text.setText(list.getName());
if (!isSelectedAll){
holder.checkbox.setChecked(false);
}
else holder.checkbox.setChecked(true);
Select all Checkbox in recycler view with data binding
In adapter assign globally boolean parameter
public boolean isAllChecked = false;
Create select all method
public void setAllChecked(boolean isAllChecked) {
this.isAllChecked = isAllChecked;
notifyDataSetChanged();
}
In onBind view to write here
if (!isAllChecked) holder.ulbCheckboxBinding.chkBoxUlbName.setChecked(false);
else holder.ulbCheckboxBinding.chkBoxUlbName.setChecked(true);
Go to your activity and used onclick listener
binding.checkSelectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter.setAllChecked(binding.checkSelectAll.isChecked());
adapter.notifyDataSetChanged();
}
});
thank you
#android

Categories

Resources