我在布局中有一个带有复选框的自定义适配器。我可以在 CheckBox 上毫无问题地使用 setOnClickListener 还是更好地使用 setOnCheckedChangeListener?
编码:
public class MyAdapter extends ArrayAdapter<Object> {
private Context context;
private LayoutInflater mInflater;
private boolean[] selected;
public MyAdaptader(Context context, List<Object> list) {
super(context, 0, list);
this.context = context;
mInflater = LayoutInflater.from(context);
selected = new boolean[list.size()];
}
private OnClickListener pressed= new OnClickListener() {
@Override
public void onClick(View v) {
if (((CheckBox) v).isChecked())
selected[(Integer)v.getTag()] = true;
else
selected[(Integer)v.getTag()] = false;
}
};
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.fila, null);
}
TextView txtName=convertView.findViewById(R.id.name);
CheckBox chkSelected = (CheckBox) convertView.findViewById(R.id.selected);
chkSelected.setTag(position);
txtName.setText(getItem(position).toString());
chkSelected.setChecked(selected[position]);
chkSelected.setOnClickListener(pressed);
return convertView;
}
}
我使用 onClick 并且似乎可以工作,但是 onCheckedListener 更好吗?
PD:没有 ViewHolder 来简化代码