How to select and store value of radio group buttons in view model with recycler view

37 Views Asked by At

`There is an app in which user will provide quantity of cupcake using edit text and in next fragment, I want to give choice of flavor selection of all cupcakes using Radio group button, that buttons will generate from one recycler view. Store all selected flavors in view Model. in short, I want choice selection like MCQ exam app.

start Fragment

detail fragment in which user input their name and quantity of cupcake

if user input 2 in detail fragment, then there will be 2 recycle viewed radio group buttons in flavor Fragment

now I want to store user choices in view model in mutable live data

1

There are 1 best solutions below

0
Pawan Harariya On
  1. You can define a listener interface in your adapter and then declare methods for each of your different radio buttons.
  2. Implement the listener interface methods in your fragment class. The interface will help get index of your recycler item as well as which radio button was clicked.
  3. Save the details in your ViewModel in an array.

You can read more about how to implement click listeners in adapter here.

Sample code :

  1. In your adapter implement interfaces for each of your radio button

    public interface ItemClickListener {
    
         // position defines which item of your recycler view is clicked
         // id defines type of flavour, you can use string or enum as per your choice
    
         void onVanillaClickListener(int id, int position);
    
         void onChocolateClickListener(int id, int position);
     }
    
  2. Set these click listeners to your appropriate radio buttons in your adapter onBindViewHolder

     @Override
     public void onBindViewHolder(ViewHolder holder, int position) {
    
         Item item = itemsList.get(position);
    
         // I have used id = 1 for vanilla, 2 = chocolate
    
         holder.vanillaRB.setOnClickListener(view -> 
                         itemClickListener.onVanillaClickListener(1, position));
    
         holder.chocolateRB.setOnClickListener(view -> 
                       itemClickListener.onVanillaClickListener(2, position))
     }
    
    
    
  3. Implement your interface methods in your fragment

    public class YourFragment extends Fragment implements 
                        YourAdapter.ItemClickListener {
       .
       .
       .
    
       @Override
       public void onVanillaClickListener(int id, int position) {
            // you can now save the id in your view model
       }
    
    
       @Override
       public void onChocolateClickListener(int id, int position) {
            // you can now save the id in your view model
       }
    
    }