簡體   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