Skip to content

Instantly share code, notes, and snippets.

@crypticminds
Last active January 19, 2020 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crypticminds/303a7b4f99bddc47f9df4369fcce175d to your computer and use it in GitHub Desktop.
Save crypticminds/303a7b4f99bddc47f9df4369fcce175d to your computer and use it in GitHub Desktop.
class MyAdapter(private val dataset: List<String>)
: RecyclerView.Adapter<MyAdapter.ViewHolder>() {
private var currentSelection = 0
/**
* The view holder.
*/
class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
lateinit var myTextView : TextView
/**
* Method that binds the data to the view.
*/
fun bindElementsToView(position: Int, selected: Boolean,
function: (Int) -> Unit ,
textToShow : String) {
myTextView = view.findViewById(R.id.content_text)
myTextView.text = textToShow
// Setting the state of the view so that the style defined in selector can be applied to it.
view.isSelected = selected
//on click the function is invoked and the currentSelection is updated.
view.setOnClickListener {
function(position)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):
ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.food_portion_list_item, parent, false)
return ViewHolder(view)
}
override fun getItemCount() = dataset.size
/**
* Binding the data into the view holder.
**/
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
/**
* This function is used to update the class variable with the current selected index and update the recycler view.
**/
val function = { pos: Int ->
if (currentSelection != pos) {
currentSelection = pos
notifyDataSetChanged()
}
}
holder.bindElementsToView(position, position == currentSelection, function , dataset[position])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment