Last active
January 19, 2020 14:06
-
-
Save crypticminds/303a7b4f99bddc47f9df4369fcce175d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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