'Image doesn't change when Radio button is pressed in android

I'm trying to change an image between three RadioButton in a RadioGroup so that each button displays a different image on the same ImageView. But it's not working, so clearly I'm missing something.

The button is declared in XML

<ImageView
    android:id="@+id/imageView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="39dp"
    android:layout_marginEnd="24dp"
    android:layout_marginBottom="24dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toStartOf="@id/guideline3"
    app:layout_constraintStart_toEndOf="@+id/guideline2"
    app:layout_constraintTop_toBottomOf="@+id/radioGroup" />

the kotlin code for the button group is:

        when (binding.radioGroup.checkedRadioButtonId) {
        binding.radioButtonLondon.id -> {
            binding.textClock.timeZone = "Europe/London"
            binding.imageView.setImageResource(R.drawable.london)
        }

        binding.radioButtonNewYork.id -> {
            binding.textClock.timeZone = "America/New_York"
            binding.imageView.setImageResource(R.drawable.newyork)
        }

        binding.radioButtonBaijing.id -> {
            binding.textClock.timeZone = "CST6CDT"
            binding.imageView.setImageResource(R.drawable.baijing)
        }

    }

but this doesn't work the image doesn't change. So what am I missing?



Solution 1:[1]

I used binding.radioGroup.checkedRadioButtonId when I should have used binding.radioGroup.setOnCheckedChangeListener { _, checkedId ->, when I did the change it solved the problem.

Solution 2:[2]

use onClickListener instead of OnCheckedChangeListener

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Wai Yan