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

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

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

    public SelectMySchoolAdapter(List 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;
    }

}

你可能感兴趣的:(Android开发)