创建一个带有复选框的列表视图。我在列表中遇到了一个问题,当我选择任何复选框时,当我向下滚动列表时,该复选框本身就没有被选中。
下面是我的代码片段:public class HomeListAdapter extends ArrayAdapter<HashMap<String, Object> > {
boolean[] itemChecked;
//
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private DisplayImageOptions options;
private CheckBox check;
public HomeListAdapter(Context context, ArrayList<HashMap<String, Object>> dataMap) {
super(context, 0, dataMap);
itemChecked = new boolean[dataMap.size()];
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.com_facebook_profile_picture_blank_square)
.showImageForEmptyUri(R.drawable.com_facebook_profile_picture_blank_square)
.showImageOnFail(R.drawable.com_facebook_profile_picture_blank_square)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.displayer(new RoundedBitmapDisplayer(20)).build();
this.notifyDataSetChanged();
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
HashMap<String, Object> dataMap = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item1, parent, false);
}
TextView description = (TextView) convertView.findViewById(R.id.description);
description.setText(dataMap.get(Home1.TAG_CNAME).toString());
TextView email = (TextView) convertView.findViewById(R.id.company);
email.setText(dataMap.get(Home1.TAG_EMAIL).toString());
check= (CheckBox) convertView.findViewById(R.id.ck);
check.setTag(getPosition(dataMap));
check.setChecked(true);
check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
}
});
if (dataMap.get(Home1.TAG_LIKE).toString().equals("true")) {
check.setChecked(true);
}else{
check.setChecked(false);
}
ImageView logo = (ImageView) convertView.findViewById(R.id.logo);
ImageLoader.getInstance().displayImage(dataMap.get(Home1.TAG_IMAGE).toString(),logo, options, animateFirstListener);
return convertView;
}
您需要在getView()
方法中设置视图的状态。您似乎已经设置了一个数组来存储选中的项目,因此您只需要在onCheckedChanged()
方法中int getPosition = (Integer) buttonView.getTag();
行之后填充它:
itemChecked[getPosition] = isChecked;
然后,在您的getView()
方法中,而不是做:
if (dataMap.get(Home1.TAG_LIKE).toString().equals("true")) {
check.setChecked(true);
}else{
check.setChecked(false);
}
你需要使用数组中的值来设置检查状态:
check.setChecked(itemChecked[position]);
如果您需要代码根据dataMap.get(Home1.TAG_LIKE)
的值设置被检查项的初始状态,它可能应该在初始化itemChecked
之后立即进入构造函数,应该是这样的:
for (int i =0; i < itemChecked.length; ++i) {
itemChecked[i] = dataMap.get(Home1.TAG_LIKE).toString().equals("true")
}