我按照教程here制作了一个复选框列表,我的适配器看起来像这样:
private class ViewHolder{
CheckBox name;
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater settingInflater = LayoutInflater.from(getContext());
if (convertView == null) {
convertView = settingInflater.inflate(R.layout.custom_row, parent, false);
holder = new ViewHolder();
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
CustomCheckbox theCheckbox = (CustomCheckbox) cb.getTag();
Toast.makeText(getContext(),
"Clicked on Checkbox: " + cb.getText(),
Toast.LENGTH_SHORT).show();
Log.e(TAG,Integer.toString(position));
});
}else{
holder = (ViewHolder)convertView.getTag();
}
}
当我启动此视图时,我的屏幕上大约有15个条目,但是当我向下滚动并选择第16个复选框时,它的位置再次回到零,并且以下条目相应地变为1,2,3 ....我如何实现持有人,以便为每个复选框获得正确的位置编号?
谢谢!
答案 0 :(得分:0)
ListView回收视图确实只有在视图未被回收时才定义点击监听器,因此当您点击“旧”监听器仍处于活动状态时
if (convertView == null) {
//here you have new view
convertView = settingInflater.inflate(R.layout.custom_row, parent, false);
holder = new ViewHolder();
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}else{
//here you get recycled view
holder = (ViewHolder)convertView.getTag();
}
//you should put you code here after you retrieve your view (either new or recycled)
holder.name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
CustomCheckbox theCheckbox = (CustomCheckbox) cb.getTag();
Toast.makeText(getContext(),
"Clicked on Checkbox: " + cb.getText(),
Toast.LENGTH_SHORT).show();
Log.e(TAG,Integer.toString(position));
});