0
我正在製作待辦事項列表應用程序,並使用listview。每個項目都有一個複選框和一個文本視圖,並有它自己的任務對象。問題是當我檢查一個盒子時,另一個盒子下面的10-11行也被檢查。如果您繼續在列表中上下滾動,則選中的複選框會傳播,並且很快它們都會被檢查。我不明白我做錯了什麼。幫助將非常感激!謝謝!Android Listview複選框獲取炒作
這裏是我的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;
}
}
你需要一個'else'爲'如果(器isChecked)'語句取消了'CheckBox'如果'isChecked'是'FALSE'。或者你可以只做'holder.checkBox.setChecked(isChecked);',並去除'if'。 –