ListView 中的复选框 - 当我选择第一个时,它会检查最后一个,反之亦然 [英] Checkboxes in a ListView - When I select the first, it checks the last and vice versa

查看:22
本文介绍了ListView 中的复选框 - 当我选择第一个时,它会检查最后一个,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了一个 ListView,其中每行都包含一个 Checkbox(以及一个 TextView).出于某种原因,当我选中"其中一个框时,它似乎会选中"ListView 中相对的框(即选择顶部框时,底部复选框变为选中状态,而顶部未选中.

I've set up a ListView that contains a Checkbox in each row (along with a TextView). For some reason, when I "check" one of the boxes, it seems to "check" whichever box is opposite in the ListView (i.e. when selecting the top box, the bottom checkbox becomes selected while the top remains unchecked.

我意识到这里没有任何代码可以使用,但我只是想知道这是否是一个普遍问题?如果没有,我可以尝试发布一些代码.谢谢!

I realize there isn't any code here to work with, but I was just wondering if this is a general problem? If not, I can try to post some code. Thanks!

推荐答案

视图在 ListView 中循环使用.这就是为什么有些人在您认为不应该被检查时被检查的原因.

Views are recycled in a ListView. That's why some are checked when you think shouldn't be.

问题是:该复选框不知道代表适配器中的哪个项目.它只是 ListView 中一行中的一个复选框.您需要做一些事情来教"行它们当前显示的数据集中的哪些项目.因此,不要使用像 String 数组这样简单的东西作为适配器的数据,而是创建一个新的模型对象,将复选框的状态存储在其中.然后,在返回 getView() 中的行之前,您可以执行以下操作:

Here's the deal: The checkbox has no idea which item in your adapter it represents. It's just a checkbox in a row in a ListView. You need to do something to "teach" the rows which item in your data set they are currently displaying. So, instead of using something as simple as a String array as the data for your adapter, create a new model object that stores the state of the checkbox in it. Then, before you return the row in getView(), you can do something like:

//somewhere in your class
private RowData getData(int position) {
return(((MyAdapter)getListAdapter()).getItem(position)); 
}



 //..then in your adapter in getView()

    RowData object = getModel(position);

     if(object.isChecked()) {
       myCheckbox.setChecked(true);
     } else {
       myCheckbox.setChecked(false);
      }

     //then retun your view.

这篇关于ListView 中的复选框 - 当我选择第一个时,它会检查最后一个,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆