Home > Software design >  Get text from Chips in a ChipGroup
Get text from Chips in a ChipGroup

Time:09-12

I am using an EditText to create chips in a ChipGroup and I want that you can't create more than one of the same tags: tag & tag as example should not be possible.

I could create an array of strings from every chip/tag but I think it's not "elegant"

This just a section of my code but the whole code is not necessary to find a solution

else if (input_video_tag.text.toString().trim().isNotEmpty() && chip_group.childCount != 0) {
     for (i in 0 until chip_group.childCount){
         if (input_video_tag.text.toString().trim() == chip_group.getChildAt(i).text.toString())
         {
            Toast.makeText(this, "You can't more than one of the same tag", Toast.LENGTH_SHORT).show()
            break
         }
     }

     addChip(input_video_tag.text.toString().trim())
     input_video_tag.setText("")
}

Thank you for your help.

CodePudding user response:

You can get the Chip using chipGroup.getChildAt(i) and then get the text with chip.text.
Something like:

    var duplicated: Boolean = false

    for (i in 0 until chipGroup.childCount) {
        if (!duplicated) {
            val chip = chipGroup.getChildAt(i) as Chip
            val chipText: String = chip.text as String

            if (chipText == newTag) duplicated = true
        } 
    }
    
    if (!duplicated){
       //add new Chip in the group
    }
  • Related