I want to implement sections in my list. I have a list of tasks. List has a custom adapter which extends recyclerview swipe adapter as I have implemented swipe gesture to th
The most simple way to split your recycler view into sections is by using a layout with the header and the item already in place and then changing the visibility if the header is the same.
Layout:
Adapter (2018 Kotlin Edition):
class ContactAdapter @Inject constructor() : RecyclerView.Adapter() {
var onItemClick: ((Contact) -> Unit)? = null
var contacts = emptyList()
override fun getItemCount(): Int {
return contacts.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_contact, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val name = contacts[position].name
holder.header.text = name.substring(0, 1)
holder.name.text = name
// if not first item, check if item above has the same header
if (position > 0 && contacts[position - 1].name.substring(0, 1) == name.substring(0, 1)) {
holder.headerTextView.visibility = View.GONE
} else {
holder.headerTextView.visibility = View.VISIBLE
}
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val headerTextView: TextView = itemView.tvHeader
val nameTextView: TextView = itemView.tvName
init {
itemView.setOnClickListener {
onItemClick?.invoke(contacts[adapterPosition])
}
}
}
}
Might be helpful as well: RecyclerView itemClickListener in Kotlin
Old Java Adapter Version:
public class RecyclerAdapter extends RecyclerView.Adapter {
private List mData;
@Inject
public RecyclerAdapter() {
mData = new ArrayList<>();
}
public void setData(List data) {
mData = data;
}
public Contact getItem(int position){
return mData.get(position);
}
@Override
public DataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_contact, parent, false);
return new DataViewHolder(itemView);
}
@Override
public void onBindViewHolder(final DataViewHolder holder, int position) {
Contact contact = mData.get(position);
holder.headerTextView.setText(contact.getName().substring(0, 1));
holder.nameTextView.setText(contact.getName());
// if not first item check if item above has the same header
if (position > 0 && mData.get(position - 1).getName().substring(0, 1).equals(contact.getName().substring(0, 1))) {
holder.headerTextView.setVisibility(View.GONE);
} else {
holder.headerTextView.setVisibility(View.VISIBLE);
}
}
@Override
public int getItemCount() {
return mData.size();
}
public class DataViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.text_header)
TextView headerTextView;
@BindView(R.id.text_name)
TextView nameTextView;
public DataViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}