RecyclerView之CheckBox实现单选效果

需求分析:动态加载支付渠道,默认选中第一个。(RecyclerView使用CheckBox实现单选功能)

解决方法:

1.在JavaBean里面添加一个boolean isSelected字段。

2.在Adapter里根据这个值设置“CheckBox”的选中状态。

3.在每次选中一个支付渠道时,改变数据源里的isSelected字段,并notifyDataSetChanged()刷新整个列表。

1.

public class ChannelBean {

    private List channellist;

    public List getChannelist() {
        return channellist;
    }

    public void setChannelList(List channellist) {
        this.channellist = channellist;
    }

    public static class ChannelsBean{
        private String channelName; //渠道名称
        private String channelValue; //渠道数据值
        private boolean isSelected; //自定义列表是否选中的标识

        public String getChannelName() {
            return channelName;
        }

        public void setChannelName(String channelName) {
            this.channelName = channelName;
        }

        public String getChannelValue() {
            return channelValue;
        }

        public void setChannelValue(String channelValue) {
            this.channelValue = channelValue;
        }

        public boolean isSelected() {
            return isSelected;
        }

        public void setSelected(boolean selected) {
            isSelected = selected;
        }
    }
}

2、3我的是在继承封装好的Adapter的convert里面实现的,你们可以在RecyclerView的Adapter的onBindViewHolder
里面实现。
package com.jieyue.jieyue.ui.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;

import com.jieyue.jieyue.R;
import com.jieyue.jieyue.model.bean.ChannelBean;

import java.util.List;

/**
 * Created by lucy on 2017/7/4.
 */

public class ChannelAdapter extends BaseQuickAdapter {
    private CheckBox checkBox;
    private int mSelectedPos = 0;   //实现单选,保存当前选中的position
    private List list;
    public ChannelAdapter(List list){
        super(R.layout.activity_recharge_channel, list);
        this.list = list;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isSelected()) {
                mSelectedPos = i;
            }
        }
    }
    @Override
    protected void convert(BaseViewHolder viewHolder, ChannelBean.ChannelsBean bean) {
        int position = viewHolder.getAdapterPosition();
        checkBox = viewHolder.getView(R.id.cb_payment_check);
        checkBox.setChecked(bean.isSelected());
        viewHolder.getView(R.id.rl_recharge_quick).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.get(mSelectedPos).setSelected(false);
                //设置新的Item勾选状态
                mSelectedPos = position;
                list.get(mSelectedPos).setSelected(true);
                notifyDataSetChanged();
            }
        });
        viewHolder.setText(R.id.tv_payment_name, bean.getChannelName());
    }
}

以上就是我的分享,欢迎指点。





你可能感兴趣的:(Android)