Add chip to chip group in dynamically of single choice style using inflating chip layout file.
Single Chip layout:
<com.google.android.material.chip.Chip
xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/ChipStyle"`enter code here`
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Single Choice Style:
<style name="ChipStyle" parent="Widget.MaterialComponents.Chip.Choice">
<item
name="chipBackgroundColor">@color/state_choice_chip_background_color</item>
<item name="android:textColor">@color/white</item>
<item name="checkedIconEnabled">false</item>
<item name="checkedIcon">@null</item>
</style>
state_choice_chip_background_color.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/red" android:state_checked="true" />
<item android:color="@color/black" />
</selector>
Method to add chips to group:
private fun addChipToGroup(person: AllQuestionData) {
val chip =LayoutInflater.from(context).inflate(R.layout.chip,
binding.chipGroup, false) as Chip
chip.text = ("Chip 1")
chip.text = person.sectionName
chip.isClickable = true
chip.isCheckable = true
chip.isChipIconVisible = false
chip.isCheckedIconVisible = false
binding.chipGroup.addView(chip as View)
chip.setOnClickListener {
viewModel.setSwipeTabs(person)
}
}
OR
Add chip to chip group in dynamically of single choice style without inflating chip layout file. directly add style selected chip color or style
private fun addChipToGroup(person: AllQuestionData) {
val chip = Chip(context,null, com.google.android.material.
R.style.Widget_MaterialComponents_Chip_Choice)
chip.text = ("Chip 1")
chip.text = person.sectionName
chip.isClickable = true
chip.isCheckable = true
chip.isChipIconVisible = false
chip.isCheckedIconVisible = false
chip.setChipBackgroundColorResource
(R.color.state_choice_chip_background_color)
chip.setTextColor(ContextCompat.getColor(requireContext(), R.color.white))
binding.chipGroup.addView(chip as View)
chip.setOnClickListener {
viewModel.setSwipeTabs(person)
}
}
Chip
programmatically. However, it would just be a matter of setting the individual relevant properties per those defined in theChoice
style; e.g.,chip.checkable = true
, etc. You can find those attributes and their values here: github.com/material-components/material-components-android/blob/…. – Orientate