我正在编写一个非常基本的检查列表应用程序。用户可以添加任务然后将其关闭。但由于某种原因,当用户检查项目时 - 列表中的位置会发生变化。这里有一些截图来说明我的意思。我的ListAdapter的代码如下:
(列表项末尾的数字是它的位置。例如Do Laundry [False] 0是位置0的项目。)
CODE
class TaskListAdapter extends ArrayAdapter<Task> implements OnCheckedChangeListener
{
Activity context;
View recycledView;
ViewAccessor viewAccessor;
CheckBox checkbox;
int position;
public TaskListAdapter(Activity context, int resource, int textViewResourceId, List<Task> objects) {
super(context, resource, textViewResourceId, objects);
this.context = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
this.recycledView = convertView;
if(recycledView == null)
{
LayoutInflater inflater = context.getLayoutInflater();
recycledView = inflater.inflate(R.layout.checkview, null);
this.viewAccessor = new ViewAccessor(recycledView);
this.recycledView.setTag(this.viewAccessor);
this.checkbox = (CheckBox) recycledView.findViewById(R.id.cbTaskCompleted);
this.checkbox.setOnCheckedChangeListener(this);
this.checkbox.setTag((Integer) position);
}else
{
viewAccessor = (ViewAccessor) this.recycledView.getTag();
this.checkbox = viewAccessor.getCheckBox();
}
this.checkbox.setText( taskList.get(position).toString()+String.valueOf(position) );
this.checkbox.setChecked( taskList.get(position).isCompleted );
return recycledView;
}
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
Task taskUnderConsideration = taskList.get( (Integer) buttonView.getTag() ) ;
taskUnderConsideration.setCompleted(isChecked);
buttonView.setText(taskUnderConsideration.toString()+buttonView.getTag().toString());
}
}
class ViewAccessor
{
View v;
CheckBox cb = null;
ViewAccessor(View v)
{
this.v = v;
}
CheckBox getCheckBox()
{
if(cb==null)
cb = (CheckBox) v.findViewById(R.id.cbTaskCompleted);
return cb;
}
}
答案 0 :(得分:1)
如果您想要显示简单的行(包含单个TextView
和CheckBox
),我建议您使用ListView
的方法:
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
它会自动显示带有CheckBox
的(内置)TextView
。