ListView中的CheckBox

点击ListView中的CheckBox时改变view的属性,同时改变User中的数据。

public class OneAdapter extends BaseAdapter {
    private Context mContext;
    private ArrayList userList;

    public OneAdapter(Context mContext, ArrayList userList) {
        this.mContext = mContext;
        this.userList = userList;
    }

    public Context getmContext() {
        return mContext;
    }

    public void setmContext(Context mContext) {
        this.mContext = mContext;
    }

    public ArrayList getList() {
        return userList;
    }

    public void setList(ArrayList userList) {
        this.userList = userList;
    }

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

    @Override
    public Object getItem(int i) {
        return userList.get(i);
    }

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

    class ViewHolder {
        CheckBox one_checkBox;
        ImageView one_image;
        TextView one_name;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        final ViewHolder viewHolder;//优化
        if (view == null) {
            viewHolder = new ViewHolder();
            view = View.inflate(mContext, R.layout.item_one, null);
            viewHolder.one_checkBox = view.findViewById(R.id.one_checkBox);
            viewHolder.one_image = view.findViewById(R.id.one_image);
            viewHolder.one_name = view.findViewById(R.id.one_name);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();

        }
        final User user = userList.get(i);
        viewHolder.one_checkBox.setChecked(user.isCheck);
        viewHolder.one_image.setImageResource(user.getImage());
        viewHolder.one_name.setText(user.getName());
       viewHolder.one_checkBox.setOnClickListener(new       View.OnClickListener() {//checkBox响应点击事件
           @Override
           public void onClick(View view) {
               if (viewHolder.one_checkBox.isChecked()){//点击CheckBox时,做出判断
                   viewHolder.one_checkBox.setChecked(true);//当发生改变时,设置view为true
                   user.setCheck(true);//将user中的内容设为true
               }else {
                   viewHolder.one_checkBox.setChecked(false);//否则设为false
                   user.setCheck(false);
               }
           }
       });
        return view;
    }

}

你可能感兴趣的:(ListView中的CheckBox)