其他分享
首页 > 其他分享> > 滚动列表视图后检查/取消选中CheckedTextView

滚动列表视图后检查/取消选中CheckedTextView

作者:互联网

我正在使用viewHolder和getview在listvew中开发checkedtextview.从数据库填充检查/取消选中状态绑定运行良好.但是,如果我检查项目,然后滚动列表视图,它将返回到取消选中状态.

这是我的customAdapter代码.

public class CustomAdapter extends ArrayAdapter<Model> {
private Activity activity;
int id;
String autoid;
ArrayList<Model> items;
DatabaseHelper dbhelper = new DatabaseHelper(getContext());

public CustomAdapter(Activity context, int resource, ArrayList<Model> obj) {
    super(context, resource, obj);

    this.activity = context;
    this.id = resource;
    this.items = obj;

    try {
        dbhelper.openDatabase();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}



static class ViewHolder {
    protected CheckedTextView textView;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder vh = null;

    if (convertView == null) {

        LayoutInflater inflater = activity.getLayoutInflater();
        convertView = inflater.inflate(id, null);
        vh = new ViewHolder();
        convertView.setTag(vh);

        vh.textView = (CheckedTextView) convertView.findViewById(R.id.textbox1);

    }
    else
    {
        vh = (ViewHolder) convertView.getTag();

    }

    final Model item = items.get(position);
    String status = item.getStatus();

    final Model check = getItem(position);

    final ViewHolder finalVh = vh;

    vh.textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            autoid = item.getAutoid();

            if (! finalVh.textView.isChecked()) {
                finalVh.textView.setChecked(true);
            }
            else
            {
                finalVh.textView.setChecked(false);
            }
        }
    });

    vh.textView.setText(item.getDate() +". "+item.getInfo());
    vh.textView.setChecked(Boolean.parseBoolean(status));

    return convertView;
}}

提前致谢.

解决方法:

那是因为您传递的列表(项目)具有旧值.更改检查状态时,将其更新为已填充到列表视图的列表(项目).在滚动时,列表视图将再次将它们加载到项目中正在获得旧的价值.

vh.textView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        autoid = item.getAutoid();

        if (! finalVh.textView.isChecked()) {
            finalVh.textView.setChecked(true);
            item.setStatus("true")
        } else {
            finalVh.textView.setChecked(false);
            item.setStatus("false");
        }
        items.set(position, item);
    }
});

标签:android-viewholder,android,listview,getview,android-checkedtextview
来源: https://codeday.me/bug/20191013/1906598.html