检查一些项目后,我的checklistview中项目的位置如何变化

时间:2011-12-24 13:27:33

标签: android android-listview

我正在编写一个非常基本的检查列表应用程序。用户可以添加任务然后将其关闭。但由于某种原因,当用户检查项目时 - 列表中的位置会发生变化。这里有一些截图来说明我的意思。我的ListAdapter的代码如下:

(列表项末尾的数字是它的位置。例如Do Laundry [False] 0是位置0的项目。)

3 items freshly added to the list one item gets checked two imes get checked

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;
        }


    }

1 个答案:

答案 0 :(得分:1)

如果您想要显示简单的行(包含单个TextViewCheckBox),我建议您使用ListView的方法:

listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

它会自动显示带有CheckBox的(内置)TextView