Skip to content

Instantly share code, notes, and snippets.

@shalperin
Created June 1, 2022 20:19
Show Gist options
  • Save shalperin/9d39c72fd80bc1247bc5deaf68d55d90 to your computer and use it in GitHub Desktop.
Save shalperin/9d39c72fd80bc1247bc5deaf68d55d90 to your computer and use it in GitHub Desktop.
Reddit code review request
enum class PAGE_TYPES {color, manufacturer}
const val noFilter = "no filter"
class ViewPagerAdapter(private val context: Context?, private val viewModel: SharedViewModel): RecyclerView.Adapter<ViewPagerAdapter.VPAViewHolder>() {
private val data = HashMap<String, List<String>>()
class VPAViewHolder(view: View?): RecyclerView.ViewHolder(view!!) {
val radioGroup:RadioGroup = view!!.findViewById<RadioGroup>(R.id.options)
val title: TextView = view!!.findViewById<TextView>(R.id.title)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VPAViewHolder {
var view = LayoutInflater.from(context).inflate(R.layout.pager_adapter_item, parent, false)
return VPAViewHolder(view)
}
override fun onBindViewHolder(holder: VPAViewHolder, position: Int) {
// which page are we on
val key = when(position) {
0 -> PAGE_TYPES.color.toString()
else -> PAGE_TYPES.manufacturer.toString()
}
// we are going to generate a radio group, get the right list of options.
val options = data[key] ?: listOf<String>()
// Set title to right message, or loading if options haven't been stocked yet
val title = if (options.isEmpty()) {
context?.resources?.getString(R.string.loading) ?: ""
} else {
context?.resources?.getString(R.string.filter, key) ?: ""
}
holder.title.setText(title)
// build the radio buttons
holder.radioGroup.removeAllViews()
options.forEachIndexed(){i, option ->
val radioButton = RadioButton(context)
radioButton.text = option
radioButton.id = i
if (key == PAGE_TYPES.manufacturer.toString() && viewModel.manufacturerFilter == option) {
radioButton.isChecked = true
}
if (key == PAGE_TYPES.color.toString() && viewModel.colorFilter == option) {
radioButton.isChecked = true
}
holder.radioGroup.addView(radioButton)
}
// bind the right check changed listener to update the view model on check.
if (key == PAGE_TYPES.manufacturer.toString()) {
holder.radioGroup.setOnCheckedChangeListener{
_, id ->
val option = options[id]
viewModel.manufacturerFilter = option
}
} else {
holder.radioGroup.setOnCheckedChangeListener{
_, id ->
val option = options[id]
viewModel.colorFilter = option
}
}
}
override fun getItemCount(): Int = 2
fun addData(key: String, options: List<String>) {
val augmentedList = options + noFilter
data[key] = augmentedList
notifyDataSetChanged()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment