繁体   English   中英

android - RecyclerView 中的单个 RadioButton

[英]android - Single RadioButton in RecyclerView

我有一个 RecyclerView,其中的项目仅包含 RadioButton,我的适配器创建了具有某些位置的 RecyclerView - 可以是 5-10 个位置,每个位置都带有 RadioButton。 但是这些 RadioButton 并不在同一个 RadioGroup 中,因为它们都在不同的 RecyclerView 位置。 有没有办法为它设置单选?

PS:我发现这个Select only one radiobutton in a recyclerview ,但这都是关于 RecyclerView 位置的 RadioGroups ,我只有 RadioButtons 。

您可以通过使用boolean变量isChecked创建模型类来管理它。

当你选择一个RadioButton首先对所有人执行isChecked = false ,然后对所选按钮执行true,然后调用notifyDataSetChanged

在适配器使用

radioButton.setChecked(list.get(position).isChecked())

它肯定会帮到你。

我有同样的问题。 根据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);                    

        });
    }
}

KOTLIN 2021 已测试

无论数据列表大小

单选 RecyclerView 只有 RadioButton 没有 RadioGroup 并经过测试

*Declare a RadioButton in a variable In your Adapter class*

    private var lastCheckedRB: RadioButton? = null

现在在您的适配器类 onBindViewHolder 中,将 OnclickListener 写入 RadioButton

holder.YOURRADIOBUTTON.setOnClickListener {
    if (lastCheckedRB!=null){
        lastCheckedRB?.isChecked=false
    }
    lastCheckedRB = holder.YOURRADIOBUTTON
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM