How to change backround color of android chips programmatically on selected state?

261 views Asked by At

i have a project that user chose a chip and backround color changes with that, in this context, i have created a backround xml file that contains selected states = true and false. Also when set backround color with this file it gets backround color hereby does not set color of selected state under this circumtances you can find sample code in below;

fragment that i set backround programmatically:


private fun createChip(label: String, time: String, id: Int): Chip {
    val chip = Chip(context, null, R.style.CustomChipStyle)

    chip.chipBackgroundColor = ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.chip_background_color))

    chip.layoutParams = LinearLayout.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT
    )

    chip.text = label
    chip.isCheckable = true
    chip.isClickable = true
    chip.setOnClickListener {
        binding.lytSelectTime.removeAllViews()

        binding.lytSelectTime


        val scrollView = HorizontalScrollView(context)
        val chipGroup = ChipGroup(context)
        chipGroup.layoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT

chip backroundColor xml file code;

<item android:color="@color/corporate_green" android:state_checked="false"/>
<item android:color="@color/corporate_blue2" android:state_selected="true"/>

Thanks in advance for your efforts...

2

There are 2 answers

1
Kishan Mevada On BEST ANSWER

Just get your checked Id and you can change your background by this snippet Programmatically.

chip.chipBackgroundColor = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.yourColorForBackground))
chip.chipStrokeColor = ColorStateList.valueOf( ContextCompat.getColor(context, R.color.yourColorForBorder))
chip.setTextColor(ColorStateList.valueOf(ContextCompat.getColor(context,R.color.edWhite)))
chip.chipStrokeWidth = 2.0f
0
Aakash Kumar On

when you are adding the chip dynamic in ChipGroup but your singleSlection is not working then make sure chip.isCheckable=true then it will work like`

val chip=Chip(this)
           chip.setText(chiparray[i])
           chip.chipBackgroundColor= ColorStateList.valueOf(ContextCompat.getColor(this, R.color.chip_background_color))
           chip.setTextColor(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.chip_text_color)))
           chip.isCheckable=true//make sure clickable is true 

          chip.setChipBackgroundColor(AppCompatResources.getColorStateList(this, R.color.chip_background_color));

          chip.setOnClickListener {
              val chip=it as Chip
              chip.isChecked=true
              categoryName=chip.text.toString()
          }
          binding.chipGrop.isSingleSelection=true
          binding.chipGrop.addView(chip)
`