`有一个应用程序,用户将使用编辑文本提供纸杯蛋糕的数量,在下一个片段中,我想使用单选组按钮提供所有纸杯蛋糕的口味选择,该按钮将从一个回收器视图生成。将所有选定的口味存储在视图模型中。简而言之,我想要像 MCQ 考试应用程序那样的选择。
现在我想将用户选择存储在可变实时数据的视图模型中
您可以在此处阅读有关如何在适配器中实现点击侦听器的更多信息。
示例代码:
在您的适配器中为每个单选按钮实现接口
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);
}
将这些点击侦听器设置为适配器中适当的单选按钮
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))
}
在片段中实现接口方法
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
}
}