Skip to content

Instantly share code, notes, and snippets.

@kevivforever
Created May 19, 2019 09:25
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 kevivforever/2b7867b879f32147ee229aa45ee18c8e to your computer and use it in GitHub Desktop.
Save kevivforever/2b7867b879f32147ee229aa45ee18c8e to your computer and use it in GitHub Desktop.
material chip
private fun setTags(tagList: List<Tag>) {
tagList.forEachIndexed { index, tag ->
val chipView = getChipView().apply {
configureChip(index, tag)
}
chipView.setOnCheckedChangeListener { chip, isChecked ->
//resId is basically a index of a tag in passed tagList
if (isChecked) {
addTagToSelectedList(chip.tag as Tag)
handleButtonDone()
} else {
removeFromSelectedList(chip.tag as Tag)
handleButtonDone()
}
}
itemView.chipGroupTags.addView(chipView)
}
}
private fun addTagToSelectedList(tag: Tag) {
selectedTagList.add(tag)
}
private fun removeFromSelectedList(tag: Tag) {
selectedTagList.remove(tag)
}
private fun handleButtonDone() {
// restriction : user must have one interest
if (selectedTagList.isEmpty()) {
itemView.buttonDone.hide()
} else {
itemView.buttonDone.show()
}
}
private fun getChipView() = LayoutInflater.from(itemView.context).inflate(R.layout.view_chip, itemView.chipGroupTags, false) as Chip
//Extension function
private fun Chip.configureChip(index: Int, tag: Tag) {
//index position of tag in the list, we will use it as the resId for the chip
this.id = index
this.text = tag.name
this.tag = tag
this.isChecked = tag.isOfUserInterest
}
@kevivforever
Copy link
Author

replace tag with your own object

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment