androidandroid-recyclerviewandroid-radiobutton

How can I change the drawable src of all radio buttons in a RecyclerView?


I have a RecyclerView with each item consisting of text and a purple radio button. There is no default radio button selected. If the user attempts to go to the next screen without selecting any radio button, I want the drawable of all the radio buttons to change from purple to red prompting the user to select one of them. Then, if the user selects one of the radio buttons, the state of all the buttons should go back to purple with the selected button in a dark purple.

In a normal list view, I could have called each button individually. How should I change the drawable of all the buttons in the recycler view on an error state?


Solution

  • I have figured out a solution to this.

    First, I added an if check inside the bind of the ViewHolder class as follows:

             fun bind(slotInfo: String, position: Int) {
                if(isError) {
                    binding.radiobutton.setBackgroundResource(R.drawable.red_circle)
                } else {
                    binding.radiobutton.setBackgroundResource(R.drawable.purple_circle)
                }
             }
    

    I update the status of the isError variable inside the activity class on error condition followed by calling the notifyDataSetChanged().

    For instance,

            fun checkForErrorCondition() {
                if(errorCondition) {
                        adapter.isError = true
                        adapter.notifyDataSetChanged()
                } 
            }
    

    Extra Info: The error condition is set inside the ViewModel class by using MutableLiveData and observed inside the activity. Whenever there is an error condition, i.e., the radio buttons are left unchecked, the checkForErrorCondition method is called inside the activity and the adapter updates the radio button drawable/background resource.