如何在具有回收器视图的视图模型中选择和存储单选组按钮的值

问题描述 投票:0回答:1

`有一个应用程序,用户将使用编辑文本提供纸杯蛋糕的数量,在下一个片段中,我想使用单选组按钮提供所有纸杯蛋糕的口味选择,该按钮将从一个回收器视图生成。将所有选定的口味存储在视图模型中。简而言之,我想要像 MCQ 考试应用程序那样的选择。

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

现在我想将用户选择存储在可变实时数据的视图模型中

android kotlin android-recyclerview android-viewmodel android-radiogroup
1个回答
0
投票
  1. 您可以在适配器中定义侦听器接口,然后为每个不同的单选按钮声明方法。
  2. 在片段类中实现监听器接口方法。该界面将帮助您获取回收站项目的索引以及单击了哪个单选按钮。
  3. 将 ViewModel 中的详细信息保存在数组中。

您可以在此处阅读有关如何在适配器中实现点击侦听器的更多信息。

示例代码:

  1. 在您的适配器中为每个单选按钮实现接口

    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. 将这些点击侦听器设置为适配器中适当的单选按钮

    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. 在片段中实现接口方法

    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
       }
    
    }
    
© www.soinside.com 2019 - 2024. All rights reserved.