Android ListView 中的checkbox

时间:2022-04-24 08:48:26

Q:ListView + CheckBox 当上下滚动的时候有事会自动选中或取消

A:这个与ListView的缓存机制有关。当你屏幕滚动后,ListView中的item选项视图先检查缓存中是否有视图,如果有就用缓存中的,不过就是更新了一下绑定的数据。这样就会存在自动选中或取消的情况。
想解决这个问题,也很简单。
你需要一个记录CheckBox状态的列表,在重写getView方法中,读取列表中记录的状态就可以了

package com.tdcontactapp.lz;

import java.util.List;

import com.tdcontactapp.R;
import com.tdcontactapp.common.RemindInfo; import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView; public class RemindAdapter extends BaseAdapter { private List<RemindInfo> list;
private Context context; public RemindAdapter(List<RemindInfo> list,Context context)
{
this.list=list;
this.context=context;
} @Override
public int getCount() {
return list.size();
} @Override
public Object getItem(int position) {
return list.get(position);
} @Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
} @Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.lz_remind_layout, null);
} TextView NameTextView=(TextView) convertView.findViewById(R.id.tvdate);
TextView TelTextView=(TextView) convertView.findViewById(R.id.tvTel);
CheckBox cb=(CheckBox)convertView.findViewById(R.id.cbflag);
TextView NoteTextView=(TextView) convertView.findViewById(R.id.tvNote); RemindInfo info=(RemindInfo)getItem(position);
final int p=position;
cb.setChecked(info.is_flag());
cb.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb=(CheckBox)v;
RemindInfo info=(RemindInfo)getItem(p);
info.set_flag(cb.isChecked());
//cb.setChecked(info.is_flag());
}
}); NoteTextView.setText(info.get_note());
try{
NameTextView.setText(info.get_date()); //TelTextView.setText(info.get_tel());
TelTextView.setText(position+"");
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return convertView;
} }