I have a default layout that holds a bunch of blank CardViews in a RecyclerView list, basically a welcome screen for the user to show them what CardViews look like. The user then launches an input screen for some data and clicks a "Save" button to save the data into a CardView. Once the user clicks Save, the layout should change from the default layout with the blank CardViews to the new, single CardView that contains the user data. Later, if the user deletes all of their CardViews, then the view should switch back to the default blank CardViews.
I'm struggling with how to set the code int the Adapter in the onCreateViewHolder because getItemCount() will already have a positive value for the default (because the RecyclerView list will already have 4 or 5 blank CardViews in it) which would conflict later with the same getItemCount() amount once the user creates 4 or 5 CardViews. Any ideas on how to set a default layout and then switch to a new layout that can then revert back to the default layout if the list is emptied of user-created CardViews?
Below is my failed attempt at laying out a test for two layouts in the Adapter. I realized it would not work because the default layout never had an ItemCount of zero since there are already 4 or 5 blank CardViews:
...
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
private List<ContactInfo> contactList;
public ContactAdapter(List<ContactInfo> contactList) {
this.contactList = contactList;
}
@Override
public int getItemCount() {
return contactList.size();
}
@Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
if(contactList.size()== 0) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.defaultcard_layout, viewGroup, false);
return new ContactViewHolder(itemView);
}
else {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.singlecard_layout, viewGroup, false);
return new ContactViewHolder(itemView);
}
}
revised Adapter and removeItem code:
...
private LayoutInflater mLayoutInflater;
private List<Contact> mContacts;
private OnItemTapListener mOnItemTapListener;
public ListContactsAdapter(Context context, List<Contact> contacts) {
Context mContext;
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContacts = contacts;
}
public void removeItem(Contact contact, int position) {
mContacts.remove(contact);
if (mContacts.size()==0) {
// if no more contacts in list,
// we rebuild from scratch
mContacts.clear();
notifyDataSetChanged();
} else {
// else we just need to remove
// one item
mContacts.remove(position);
notifyItemRemoved(position);
}
}