How To Get Selected Chips From Chipgroup?
I search a lot on internet but couldn't find the exact solution. Here is the link that i last tried from SO. Get selected Chips from a ChipGroup I want to get selected chips from c
Solution 1:
Starting with the version 1.2.0 you can use the method chipGroup.getCheckedChipIds()
List<Integer> ids = chipGroup.getCheckedChipIds();
for (Integer id:ids){
Chip chip = chipGroup.findViewById(id);
//....
}
OLD ANSWER with 1.1.0:
currently there isn't a direct API to get the selected chips.
However you can iterate through the children of the ChipGroup
and check chip.isChecked()
.
ChipGroupchipGroup= findViewById(R.id.....);
for (int i=0; i<chipGroup.getChildCount();i++){
Chipchip= (Chip)chipGroup.getChildAt(i);
if (chip.isChecked()){
//this chip is selected.....
}
}
Solution 2:
the solution I used in Kotlin with data binding
mBinding?.chipGroup?.children
?.toList()
?.filter { (it as Chip).isChecked }
?.forEach { //here are your selected chips as 'it' }
And here is how I got just titles
mBinding?.chipGroup?.children
?.toList()
?.filter { (it asChip).isChecked }
?.joinToString(", ") { (it asChip).text }
Solution 3:
Get selected chip's text in a chip group
To get selected chip's text from chipgroup, you can use this one liner in Kotlin:
val selectedChipText = parentChipGroup.findViewById<Chip>(parentChipGroup.checkedChipId).text.toString()
Solution 4:
I used below mentioned method to detect the selected chips in chipGroup.
for (chipTitle in stringList) {
valchip= Chip(chipGroup.context)
chip.text = chipTitle
chip.tag = chipTitle
chip.isClickable = true
chip.isCheckable = true
chip.setOnCheckedChangeListener { _, isChecked ->
if (isChecked){
Log.e(TAG, chipTitle)
}
}
chipGroup.addView(chip)
}
chipGroup.isSingleSelection = true
Solution 5:
Now using Material Chip it is very easy task. Here example of getting chip's text from a dialog
val builder = AlertDialog.Builder(requireContext())
builder.setTitle("Filter")
val mView = FilterOptionLayoutBinding.inflate(layoutInflater)
builder.setView(mView.root)
builder.setPositiveButton(android.R.string.ok) { d, p ->
mView.chipGroup.checkedChipIds.forEach {
val chip = mView.root.findViewById<Chip>(it).text.toString()
checkedChipsText.add(chip)
}
d.dismiss()
}
builder.setNegativeButton(android.R.string.cancel) { d, _ ->
d.cancel()
}
builder.create()
builder.show()
now chip hold text of all chips
Post a Comment for "How To Get Selected Chips From Chipgroup?"