使用RecyclerView上的多个单选按钮,一个选择单选按钮

时间:2019-02-14 11:51:33

标签: android

 @Override
    public void onBindViewHolder(@NonNull StateViewHolder stateViewHolder, int i) {
            GetStateApiResponse getStateApiResponse = state.get(i);
        stateViewHolder.btnstate.setText(getStateApiResponse.getStateName().toString());
        stateViewHolder.disttCount.setText(getStateApiResponse.getCount().toString());

       stateViewHolder.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
           @Override
           public void onCheckedChanged(RadioGroup group, int checkedId) {

               RadioButton checked_rb = group.findViewById(checkedId);

               if (lastChecked != null) {
                   lastChecked.setChecked(false);
               }
               //store the clicked radiobutton
               lastChecked = checked_rb;
           }
       });   

}

如果我单击单选按钮而不是自动取消选中,则此代码在recyclerview上无法正常工作

2 个答案:

答案 0 :(得分:1)

我认为这是因为lastChecked是一个实例变量,并且包含所有列表项的状态。您可以通过为列表中的每个项目指定一个lastChecked变量来解决此问题。

答案 1 :(得分:0)

此问题的正确答案

private RadioButton lastChecked
...
    @Override
        public void onBindViewHolder(@NonNull StateViewHolder stateViewHolder, int i) {
                GetStateApiResponse getStateApiResponse = state.get(i);
            stateViewHolder.btnstate.setText(getStateApiResponse.getStateName().toString());
            stateViewHolder.disttCount.setText(getStateApiResponse.getCount().toString());


            if (lastChecked!=null && lastCheckedPos!=-1 && i==lastCheckedPos)
            {
                lastChecked.setChecked(true);
            }
            else
            {
                stateViewHolder.btnstate.setChecked(false);
            }



            stateViewHolder.btnstate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    for(GetStateApiResponse tempModel: state)
                        tempModel.setSetchecked(false);

                    state.get(i).setSetchecked(true);
                    lastCheckedPos=i;

                    if(null != lastChecked && !v.equals(lastChecked))
                        lastChecked.setChecked(false);
                    lastChecked = (RadioButton) v;
                    lastChecked.setChecked(true);


                }
            });


        }