gpt4 book ai didi

java - 动态构建的复选框在滚动时被重置

转载 作者:行者123 更新时间:2023-12-02 11:07:54 24 4
gpt4 key购买 nike

我有一个带有适配器的 ListView ,我在其中创建了一些复选框,在适配器中我添加了一个更改监听器来更改 Realm 数据库中的值。就在上面,我获取了存储在数据库中的当前值,以保留以前的值。

这似乎工作得相当好,但是当您滚动时,已选中的项目在经过屏幕后将变为未选中状态。

如下所示:

enter image description here enter image description here

生成此代码的代码:

适配器.java

if(check != null){
viewHolder.checkbox.setText(check.title);

if (check.completed == 1) {
viewHolder.checkbox.setChecked(true);
} else {
viewHolder.checkbox.setChecked(false);
}

viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

if (isChecked) {
check.setCompleted();
} else {
check.setNotCompleted();
}
}
});
}

fragment .java

final ChecksAdaptor checksAdaptor = new ChecksAdaptor(device.checks(), getContext());

listView.setAdapter(checksAdaptor);

完整适配器

public class ChecksAdaptor extends ArrayAdapter<DeviceCheck> {

public RealmResults<DeviceCheck> checks;

Context mContext;

// View lookup cache
private static class ViewHolder {
CheckBox checkbox;
}

public ChecksAdaptor(RealmResults<DeviceCheck> checks, Context context) {
super(context, R.layout.check_row_item, checks);
this.checks = checks;
this.mContext=context;
}

private int lastPosition = -1;

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

// Get the data item for this position
final DeviceCheck check = getItem(position);

// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag

final View result;

if (convertView == null) {

viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.check_row_item, parent, false);
viewHolder.checkbox = convertView.findViewById(R.id.checkbox);

result=convertView;

convertView.setTag(viewHolder);

} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}

lastPosition = position;

if(check != null){
viewHolder.checkbox.setText(check.title);

if (check.completed == 1) {
viewHolder.checkbox.setChecked(true);
} else {
viewHolder.checkbox.setChecked(false);
}

viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

if (isChecked) {
check.setCompleted();
} else {
check.setNotCompleted();
}
}
});
}

// Return the completed view to render on screen
return convertView;
}
}

最佳答案

根据mTak的建议

viewHolder.checkbox.setOnCheckedChangeListener(null)

关于java - 动态构建的复选框在滚动时被重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50800999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com