Android中使用ListView点击item时修改选中状态(item使用RadioButton)

这是列表是使用ListView ,如果使用RecycleView的话,也是一样的,布局就不说了,activity中的写法不变,这里只需要注意adapter里面的写法就OK了!

public class SelectMySchoolAdapter extends BaseAdapter {
    private List<SelectSchoolBean>  schoolList;
    private Activity activity;
    private int temp = -1;//记录每次点击的按钮的Id

    public SelectMySchoolAdapter(List<SelectSchoolBean> schoolList, Activity activity) {
        this.schoolList = schoolList;
        this.activity = activity;
    }

    @Override
    public int getCount() {
        return schoolList.size();
    }

    @Override
    public Object getItem(int position) {
        return schoolList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null){
            holder = new ViewHolder();
            convertView = LayoutInflater.from(activity).inflate(R.layout.my_all_school_item,null);
            holder.textView    = convertView.findViewById(R.id.schoolItem);
            holder.radioButton = convertView.findViewById(R.id.isSelectEd);
            convertView.setTag(holder);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.textView.setText(schoolList.get(position).getSchoolName());

        holder.radioButton.setId(position); //把RadioButton的Id设置为position
        holder.radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked){//如果是选中状态
                    //temp不为-1,说明已经进行过点击事件
                    if (temp != -1){
                        RadioButton tempButton = activity.findViewById(temp);
                        if (tempButton != null){
                            //取到上一次点击的RadioButton,并设置为未选中状态
                            tempButton.setChecked(false);
                        }
                    }
                    //将temp重新赋值,记录下本次点击的RadioButton
                    temp = buttonView.getId();
                }
            }
        });

        if (position == temp){
            //将本次点击的RadioButton设置为选中状态
            holder.radioButton.setChecked(true);
        } else {
            holder.radioButton.setChecked(false);
        }

        return convertView;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值