【发布时间】:2014-02-16 05:32:56
【问题描述】:
我有一个用于列表视图的 ArrayAdapter,其中包含多个按钮。对于一个切换按钮,我希望有一个基于条件的默认状态,并让用户也切换按钮。
但是,当用户单击第 1 行上的按钮时,第 3 行的按钮实际上被选中。我不确定为什么会这样。下面是来自我的getView 方法与 cmets 的相关代码的 sn-p。
我的切换按钮布局
<ToggleButton android:id="@+id/color_toggle"
android:layout_width="50px"
android:layout_height="50px"
android:focusable="false"
android:textOn="" android:textOff="" android:layout_alignParentLeft="true"
android:layout_marginRight="10dp"
/>
class Color {
int id;
int something;
}
List<Color> colorsList;
class ColorHolder {
TextView colorNameText;
ToggleButton toggleButton;
}
public View getView(final int position, final View convertView, final ViewGroup parent) {
View rowView = convertView;
Color c = colorsList.get(position);
if (null == rowView) {
rowView = this.inflater.inflate(R.layout.list_item_color, parent, false);
holder = new ColorHolder();
holder.colorNameText = (TextView) rowView.findViewById(R.id.color_name);
holder.toggleButton = (ToggleButton) rowView.findViewById(R.id.color_toggle);
rowView.setTag(holder);
}
else {
holder = (ColorHolder)rowView.getTag();
}
holder.toggleButton.setTag(c.getId());
final ColorHolder thisRowHolder = holder;
holder.toggleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (thisRowHolder.toggleButton.isChecked()) {
thisRowHolder.toggleButton.setBackgroundDrawable(//normal button);
thisRowHolder.toggleButton.setChecked(false);
for (int i = 0; i < colorList.size(); i++) {
if (colorList.get(i) == (Integer)v.getTag()) {
colorList.get(i).setSomething(0);
break;
}
}
adapter.notifyDataSetChanged();
}
else {
thisRowHolder.toggleButton.setBackgroundDrawable(//enabled button);
thisRowHolder.toggleButton.setChecked(true);
for (int i = 0; i < colorList.size(); i++) {
if (colorList.get(i) == (Integer)v.getTag()) {
colorList.get(i).setSomething(1);
break;
}
}
adapter.notifyDataSetChanged();
}
}
});
if (c.getSomething()>0) {
holder.toggleButton.setBackgroundDrawable(//enabled button);
holder.toggleButton.setChecked(true);
}
else {
holder.toggleButton.setBackgroundDrawable(//normal button);
holder.toggleButton.setChecked(false);
}
return rowView;
}
问题
我做错了什么?为什么即使我正在切换第一行中的按钮,第三行中的其他按钮也会切换。
我读到这是因为 listView 回收了,有没有办法解决它?基于类似的问题,我尝试了一些策略,但无济于事:1)将onClickListener 放在if 子句中。 2)而不是在setTag中设置int,而是设置holder并在onClickListener中使用holder
更新
我已根据收到的建议更新了问题中的所有代码。
【问题讨论】:
-
发生这种情况 bcoz listview 回收视图
-
我读到...有没有办法解决这个问题?
-
很好的解释。但是,我注意到在您提供的示例中,您正在更改列表中的值,然后调用 notify。但是,我相信我的情况有点不同,因为我正在更改与数据列表无关的列表项中按钮的属性。所以调用 notify 是没有意义的。
-
我发帖是为了暗示它是如何工作的。由你来修改。
标签: java android android-listview android-arrayadapter