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

301 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

You can get the View for each child in a Recycler View, and from that View you can reference the radio button and change its drawable. Example below:

RecyclerView.ViewHolder holder = recyclerView.findViewHolderForAdapterPosition(position);
RadioButton button = holder.itemView.findViewById(R.id.radio_button);
button.setBackgroundResource(R.drawable.purple_background);

Now it's just a matter of iterating all the RecyclerView's children and changing the background resource for the RadioButtons.

You can iterate using this code:

for (int i = 0; i < recyclerView.getChildCount(); i++) {
     //do something here
}

You can now change all the RecyclerView's children radio button backgrounds like this:

for (int i = 0; i < recyclerView.getChildCount(); i++) {
     //change the background to purple
     RecyclerView.ViewHolder holder = recyclerView.findViewHolderForAdapterPosition(position);
     RadioButton button = holder.itemView.findViewById(R.id.radio_button);
     button.setBackgroundResource(R.drawable.purple_background);
}