滚动自定义ListView时,复选框值会更改

时间:2012-07-05 11:53:09

标签: android listview checkbox


我拥有的内容:带有Textviews和复选框的自定义列表视图。


问题:假设我的屏幕每次只能显示6个列表,其他列表不可见。 所以我检查了列表中的第一个元素(位置0处的项目)。我向下滚动以查看我的所有列表,当我向上滚动第一个元素(位置0处的项目)时,正确选中了复选框。大!但现在也检查了新的项目,例如位置8的项目(因为当我滚动列表时(对于环形),它成为位置0的新项目。我的屏幕在时间上只显示7个元素)。它会被检查,但我从未检查过它!

问题:我怎么能避免这个问题?我不希望我没有单击的复选框更改其状态。
在我的适配器下面的listView和getView函数,我已经实现了setOnCheckedChangeListener:

public class NewQAAdapterSelectFriends extends BaseAdapter {
private LayoutInflater mInflater;
private Person[] data;


public NewQAAdapterSelectFriends(Context context) { 
    mInflater = LayoutInflater.from(context);
}

public void setData(Person[] data) {
    this.data = data;
}

@Override
public int getCount() {
    return data.length;
}

@Override
public Object getItem(int item) {
    return data[item];
}

@Override
public long getItemId(int position) {
    return position;
}



@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.item_select_friends, null);
        final ViewHolder viewHolder = new ViewHolder();
        viewHolder.nameText=(TextView) convertView.findViewById(R.id.personName);
        viewHolder.surnameText=(TextView) convertView.findViewById(R.id.personSurname);
        viewHolder.contactImage=(ImageView) convertView.findViewById(R.id.personImage);
        viewHolder.checkBox=(CheckBox)convertView.findViewById(R.id.checkBox);
        convertView.setTag(viewHolder);
        viewHolder.nameText.setTag(viewHolder.nameText);
        viewHolder.nameText.setTag(viewHolder.surnameText);
        viewHolder.contactImage.setTag(data[position]);
        viewHolder.checkBox.setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                        Person element = (Person) viewHolder.checkBox.getTag();

                        if(isChecked){
                            element.setCheck(buttonView.isChecked());
                            //data[position].setCheck(true); //this is equivalent to previous line

                        }
                        else{
                            //to-do

                        }

                    }
                });
        viewHolder.checkBox.setTag(data[position]);

    } else {


    }

     ViewHolder holder = (ViewHolder) convertView.getTag();
     holder.nameText.setText(data[position].getName());
     holder.surnameText.setText(data[position].getSurname());
     holder.contactImage.setImageResource(data[position].getPhotoRes());
     holder.contactImage.setScaleType(ScaleType.FIT_XY);
     holder.checkBox.setChecked(data[position].isCheck());
    return convertView;
}

static class ViewHolder {
    TextView nameText;
    TextView surnameText;
    ImageView contactImage;
    CheckBox checkBox;
}
}

感谢您的回答:)

编辑:根据建议我改变了我的getView,如下所示:

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    final ViewHolder viewHolder;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.item_select_friends, null);
        viewHolder=new ViewHolder();
        viewHolder.nameText=(TextView) convertView.findViewById(R.id.personName);
        viewHolder.surnameText=(TextView) convertView.findViewById(R.id.personSurname);
        viewHolder.contactImage=(ImageView) convertView.findViewById(R.id.personImage);
        viewHolder.checkBox=(CheckBox)convertView.findViewById(R.id.checkBox);

        convertView.setTag(viewHolder);

        viewHolder.nameText.setTag(viewHolder.nameText);
        viewHolder.nameText.setTag(viewHolder.surnameText);
        viewHolder.contactImage.setTag(data[position]);
        viewHolder.checkBox.setChecked(data[position].isCheck());  
        viewHolder.checkBox.setOnClickListener(new OnClickListener() {  

            public void onClick(View arg0) {  

                if(viewHolder.checkBox.isChecked()==true)   
                    data[position].setCheck(true);  
                else  
                    data[position].setCheck(false);  
            }  
        }); 

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

    viewHolder.nameText.setText(data[position].getName());
    viewHolder.surnameText.setText(data[position].getSurname());
    viewHolder.contactImage.setImageResource(data[position].getPhotoRes());
    viewHolder.contactImage.setScaleType(ScaleType.FIT_XY);
    viewHolder.checkBox.setChecked(data[position].isCheck());
    return convertView;
}

编辑后的情况:现在,如果我检查屏幕上显示的初始项目,然后我仔细检查列表,则会正确保存它们的值。但是当我滚动列表时,例如我想检查列表中的最后一个树复选框,然后在滚动后它们变得未被检查....但是为什么??????

已解决:我用以下代码解决了我的getView问题:

    public class NewQAAdapterSelectFriends extends BaseAdapter {
private LayoutInflater mInflater;
private Person[] data;
boolean[] checkBoxState;
ViewHolder viewHolder;

public NewQAAdapterSelectFriends(Context context) { 
    mInflater = LayoutInflater.from(context);
}


public void setData(Person[] data) {
    this.data = data;
    checkBoxState=new boolean[data.length];
}

@Override
public int getCount() {
    return data.length;
}

@Override
public Object getItem(int item) {
    return data[item];
}

@Override
public long getItemId(int position) {
    return position;
}



@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.item_select_friends, null);
        viewHolder=new ViewHolder();

        viewHolder.nameText=(TextView) convertView.findViewById(R.id.personName);
        viewHolder.surnameText=(TextView) convertView.findViewById(R.id.personSurname);
        viewHolder.contactImage=(ImageView) convertView.findViewById(R.id.personImage);
        viewHolder.checkBox=(CheckBox)convertView.findViewById(R.id.checkBox);

        convertView.setTag(viewHolder);

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

    viewHolder.nameText.setText(data[position].getName());
    viewHolder.surnameText.setText(data[position].getSurname());
    viewHolder.contactImage.setImageResource(data[position].getPhotoRes());
    viewHolder.contactImage.setScaleType(ScaleType.FIT_XY);
    viewHolder.checkBox.setChecked(checkBoxState[position]);
    viewHolder.checkBox.setOnClickListener(new View.OnClickListener() {

           public void onClick(View v) {
               if(((CheckBox)v).isChecked()){
                   checkBoxState[position]=true;
                   data[position].setCheck(true);
               }else{
                   checkBoxState[position]=false;
                   data[position].setCheck(false);
               }
            }
        });
    return convertView;
}


static class ViewHolder {
    TextView nameText;
    TextView surnameText;
    ImageView contactImage;
    CheckBox checkBox;
}

}

我已经看过这个教程来做我的getView:http://androidcocktail.blogspot.it/2012/04/adding-checkboxes-to-custom-listview-in.html

8 个答案:

答案 0 :(得分:5)

我解决了我的问题只是将“setOnCheckedChangeListener”更改为“setOnClickListener”

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

    ViewHolder holder;

    if (convertView == null) {

        CheckBox cbItemChecklist = new CheckBox(context);

        holder = new ViewHolder();
        holder.cbItemChecklist = cbItemChecklist;

        convertView = cbItemChecklist;
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    final ItemChecklist itemChecklist = itensChecklist.get(position);

    holder.cbItemChecklist.setText(itemChecklist
            .getDescricaoItemChecklist());
    holder.cbItemChecklist.setChecked(itemChecklist.isChecked());
    holder.cbItemChecklist
            .setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if(itemChecklist.isChecked()){
                        itemChecklist.setChecked(false);
                    } else {
                        itemChecklist.setChecked(true);                         
                    }


                }
            });
    return convertView;
}

答案 1 :(得分:4)

检查以下代码 -

public View getView(int position, View convertView, ViewGroup parent){
            View view = convertView;
            ViewHolder holder = new ViewHolder();

            if(view == null){

                view = inflater.inflate(R.layout.list_callcycle_blue, null);                
                holder.llContainer = (LinearLayout) view.findViewById(R.id.ll_container);
                holder.lblLabel = (TextView) view.findViewById(R.id.txt_desc);
                holder.cb = (CheckBox) view.findViewById(R.id.cb_store);

                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }

            final Object data = getItem(position);
            holder.lblLabel.setText(data.getDescription());

            holder.cb.setTag(position);
            holder.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    int position = (Integer) buttonView.getTag();
                    objects.get(position).setChecked(buttonView.isChecked());
                }
            });
            holder.cb.setChecked(isChecked(position));

            return view;
        }

请始终牢记,在设置数据之前使用更改holder.cb.setOnCheckedChangeListener() 任何侦听器,在我们的示例中为holder.cb.setChecked()

原因:当我们滚动时,listview将回收视图,因此如果在侦听器之前使用setchecked,那么它将在旧侦听器的基础上选择值。如果我们在监听器之后设置它,那么它将采用最新值

答案 2 :(得分:2)

仅当convertview为null时,才设置复选框的标记。这仅发生在第一个记录屏幕上。当用户向下滚动时,之前的转换视图将被回收。因此,您的复选框将旧数据项作为其标记。

您选中的更改侦听器应如下所示:

new CompoundButton.OnCheckedChangeListener()
{
    @Override
    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked)
    {
        Person element = (Person) viewHolder.checkBox.getTag();

        data[position].setCheck(isChecked);

        if(isChecked)
        {
            // do your stuff
        }
        else
        {
            //to-do
        }

    }
}

答案 3 :(得分:1)

你没有覆盖convertView!= null的情况,这是向上和向下滚动时发生的情况。您应该实现一种方法来回收convertView(更好),或者只是忽略它并在这种情况下给出一个全新的视图(更糟)。

答案 4 :(得分:0)

检查此代码

public class NewQAAdapterSelectFriends extends BaseAdapter {
private LayoutInflater mInflater;
private Person[] data;
ArrayList<String> checkedItem=new ArrayList<String>();

public NewQAAdapterSelectFriends(Context context) { 
    mInflater = LayoutInflater.from(context);
}

public void setData(Person[] data) {
    this.data = data;
}

@Override
public int getCount() {
    return data.length;
}

@Override
public Object getItem(int item) {
    return data[item];
}

@Override
public long getItemId(int position) {
    return position;
}



@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.item_select_friends, null);
        final ViewHolder viewHolder = new ViewHolder();
        viewHolder.nameText=(TextView) convertView.findViewById(R.id.personName);
        viewHolder.surnameText=(TextView) convertView.findViewById(R.id.personSurname);
        viewHolder.contactImage=(ImageView) convertView.findViewById(R.id.personImage);
        viewHolder.checkBox=(CheckBox)convertView.findViewById(R.id.checkBox);
        convertView.setTag(viewHolder);
        viewHolder.nameText.setTag(viewHolder.nameText);
        viewHolder.nameText.setTag(viewHolder.surnameText);
        viewHolder.contactImage.setTag(data[position]);
        viewHolder.checkBox.setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                        Person element = (Person) viewHolder.checkBox.getTag();

                        if(isChecked){
                            getCheckList(data[position],isChecked);
                        }
                        else{
                            getCheckList(data[position],isChecked);    
                        }

                    }
                });
        viewHolder.checkBox.setTag(data[position]);
    } 
     ViewHolder holder = (ViewHolder) convertView.getTag();
     holder.nameText.setText(data[position].getName());
     holder.surnameText.setText(data[position].getSurname());
     holder.contactImage.setImageResource(data[position].getPhotoRes());
     holder.contactImage.setScaleType(ScaleType.FIT_XY);
     if(checkedItem != null && checkedItem.contains(data[position])){
        viewHolder.checkBox.setChecked(true);
     }else
     {
        viewHolder.checkBox.setChecked(false);
     } 
    return convertView;
}

static class ViewHolder {
    TextView nameText;
    TextView surnameText;
    ImageView contactImage;
    CheckBox checkBox;
}
public void getCheckList(String value,boolean status){
        if(!checkedItem.contains(value)  && status)
        {
            checkedItem.add(value);
        }
        if(checkedItem.contains(value)  && !status)
        {
            checkedItem.remove(value);
        }
    }
}

答案 5 :(得分:0)

我有一个很好的替代CheckBox。您可以将android:state_activated="true"用于ListView行。它不会丢失其状态,也不需要大量代码。

以下是如何运作

  • 在可绘制文件夹中创建active_row.xml


<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_activated="true"        
          android:drawable="@android:color/darker_gray"/>
 </selector>   
  • 将行布局的背景设置为android:background="@drawable/active_row.xml"
  • 最后将其添加到ListView中 android:choiceMode="multipleChoice"

您可以像这样检查每一行的状态

View v;

LinearLayout yourRowLayout;
for (int i = 0; i < yourListView.getChildCount(); i++) {
v = yourListView.getChildAt(i);
yourRowLayout = (LinearLayout) v.findViewById(R.id. yourRowLayout);
if(yourRowLayout.isActivated()){....  }  }

答案 6 :(得分:0)

在适配器中使用 setTag()。您可以在此处查看示例Example listview with checkbox scroll issue

答案 7 :(得分:0)

您需要更新适配器以保留复选框

的值
holder.chk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckBox c = (CheckBox)v.findViewById(R.id.chkID);
                Boolean chk = c.isChecked();
                Integer pos = (Integer)v.getTag();
                itemList.get(pos).setChk(chk);

            }
        });

如需更多帮助,请参阅Retain Checkbox value

中的这篇文章