Skip to content

Instantly share code, notes, and snippets.

@Jeff-Soares
Created September 18, 2021 21:49
Show Gist options
  • Save Jeff-Soares/7485a420dfdd56908bf809b3061bd8a7 to your computer and use it in GitHub Desktop.
Save Jeff-Soares/7485a420dfdd56908bf809b3061bd8a7 to your computer and use it in GitHub Desktop.
RecyclerView Adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class CustomAdapter : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
private var list: MutableList<String> = mutableListOf()
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(viewGroup.context)
.inflate(R.layout.item_model, viewGroup, false)
return ViewHolder(view)
}
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
viewHolder.textView.text = list[position]
}
override fun getItemCount() = list.size
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textView: TextView
init {
textView = itemView.findViewById(R.id.name)
}
}
fun setList(list: MutableList<String>) {
this.list = list
notifyDataSetChanged()
}
fun clearList() {
list = mutableListOf()
notifyDataSetChanged()
}
fun addItem(item: String){
list.add(item)
notifyDataSetChanged()
}
fun removeItem(position: Int) {
list.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, itemCount)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment