我正在制作一个待办事项列表应用,我使用了listview。每个项目都有一个复选框和一个textview,并拥有自己的Task对象。问题是当我检查一个盒子时,另一个盒子下面10-11行也会被检查。如果您继续在列表中向上和向下滚动,则会选中已选中的复选框,并且很快就会检查所有这些复选框。我不明白我做错了什么。帮助将非常感谢!谢谢!
这是我的ListAdapter:
public class TaskListAdapter extends BaseAdapter {
private ArrayList<Task> tasks;
private Context context;
private TinyDB tinyDB;
public TaskListAdapter(Context context, ArrayList<Task> tasks, TinyDB tinyDB){
this.context = context;
this.tasks = tasks;
this.tinyDB = tinyDB;
}
@Override
public int getCount() {
return tasks.size();
}
@Override
public Object getItem(int position) {
return tasks.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
static class ViewHolder {
AppCompatCheckBox checkBox;
TextView taskTextView;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView = layoutInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.checkBox = (AppCompatCheckBox) convertView.findViewById(R.id.checkBox);
holder.taskTextView = (TextView) convertView.findViewById(R.id.taskTextView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//checkbox
int priority = tasks.get(position).getPriority();
int[][] states = new int[][]{new int[]{-android.R.attr.state_checked}, new int[]{android.R.attr.state_checked}};
int[] redColors = new int[]{context.getResources().getColor(R.color.radioBtnRed), context.getResources().getColor(R.color.radioBtnRed),};
int[] blueColors = new int[]{context.getResources().getColor(R.color.radioBtnBlue), context.getResources().getColor(R.color.radioBtnBlue),};
int[] greenColors = new int[]{context.getResources().getColor(R.color.radioBtnGreen), context.getResources().getColor(R.color.radioBtnGreen),};
if(priority == 1){
holder.checkBox.setSupportButtonTintList(new ColorStateList(states, redColors));
}
else if(priority == 2){
holder.checkBox.setSupportButtonTintList(new ColorStateList(states, blueColors));
}
else if(priority == 3){
holder.checkBox.setSupportButtonTintList(new ColorStateList(states, greenColors));
}
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
tasks.get(position).setIsChecked(isChecked);
tinyDB.putListObject(MainActivity.TASKS_FILE, tasks);
MainActivity.collectCheckedTasks();
}
});
boolean isChecked = tasks.get(position).isChecked();
if(isChecked){
holder.checkBox.setChecked(true);
}
//task title
String title = tasks.get(position).getTitle();
holder.taskTextView.setText(title);
return convertView;
}
}
答案 0 :(得分:0)
您的代码
if(isChecked){
holder.checkBox.setChecked(true);
}
如果isChecked
为真,则将复选框设置为选中状态,但如果isChecked
为假,则不执行任何操作。选中的复选框保持选中状态,但应取消选中。
尝试更改为
holder.checkBox.setChecked(isChecked);