Den*_*Den 2 java android android-radiobutton android-recyclerview
我有一个仅包含RadioButton的物品的RecyclerView,我的适配器创建了一些位置的RecyclerView - 可以在每个位置使用RadioButton 5-10个位置.但是这些RadioButton不在同一个RadioGroup中,因为它们都处于不同的RecyclerView位置.有没有办法为它设置单一选择?
PS:我发现这只在recyclerview中选择了一个radiobutton,但它完全是关于RecyclerView位置的RadioGroups,我只有RadioButtons.
您可以通过创建带boolean变量的模型类来管理它isChecked.
当你选择RadioButton第一个isChecked = false为所有人做,然后为你选择的按钮生效,然后打电话notifyDataSetChanged.
在适配器使用
radioButton.setChecked(list.get(position).isChecked())
Run Code Online (Sandbox Code Playgroud)
它肯定会帮到你.
我有同样的问题。根据 Vishal Chhodwani 的回答,我写了以下解决方案,希望它可以帮助其他读者。
class MyRecycler extends RecyclerView.Adapter<MyRecycler.RecyclerViewHolder> {
static class RecyclerViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.aRadioButton)
RadioButton rb;
public RecyclerViewHolder(View itemView, int viewType, final Context context) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
private List<MyModel> list;
private RadioButton selectedRadioButton;
// Constructor and other methods here...
@Override
public void onBindViewHolder(final MyRecycler.RecyclerViewHolder holder, int position) {
RadioButton radioButton = holder.rb;
radioButton.setChecked(list.get(position).isChecked());
radioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Set unchecked all other elements in the list, so to display only one selected radio button at a time
for(MyModel model: list)
model.setChecked(false);
// Set "checked" the model associated to the clicked radio button
list.get(position).setChecked(true);
// If current view (RadioButton) differs from previous selected radio button, then uncheck selectedRadioButton
if(null != selectedRadioButton && !v.equals(selectedRadioButton))
selectedRadioButton.setChecked(false);
// Replace the previous selected radio button with the current (clicked) one, and "check" it
selectedRadioButton = (RadioButton) v;
selectedRadioButton.setChecked(true);
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5478 次 |
| 最近记录: |