【发布时间】:2015-04-01 08:48:43
【问题描述】:
我有一个带有listView的片段,listview布局包含(TextView、checkBox和ImageView如下
t1........CB.......IV
t2........CB.......IV
t3........CB.......IV
t4........CB.......IV
t5........CB.......IV
t6........CB.......IV
SaveButton
在 getView() 方法中,我检查复选框是否被选中,如果被选中,我将选中的项目添加到列表中。
问题是,最初我将所有复选框设置为未选中,但是当我选中第一项时,令人惊讶的是,自动选中下面的第三项,如果我从上面选中第二项,则第二项从下面检查,如果我从上面检查第三项,那么最后一项会自动检查?!!
请看一下 getView() 方法,让我知道我错过了什么:
getView():
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater layoutinflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutinflater.inflate(R.layout.list_items_layout, null);
}
if (this.checkedItemsList == null) {
this.checkedItemsList = new ArrayList<String>();
}
final TextView tv = (TextView) convertView.findViewById(R.id.tvlist_topic);
final CheckBox cb = (CheckBox) convertView.findViewById(R.id.cbList_hook);
final ImageView iv = (ImageView) convertView.findViewById(R.id.ivList_delete);
tv.setText(this.topicsList.get(position));
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
checkedItemsList.add(topicsList.get(position));
setCheckedItemsList(checkedItemsList);
Log.d(TAG, "size: " + checkedItemsList.size());
}
}
});
iv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (cb.isChecked())
cb.setChecked(false);
topicsList.remove(position);
notifyDataSetChanged();
}
});
return convertView;
}
xml:
<RelativeLayout
android:id="@+id/rl2_List"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@id/rl1_List"
android:layout_centerInParent="true">
<CheckBox
android:id="@+id/cbList_hook"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:checked="false"/>
</RelativeLayout>
<RelativeLayout
android:id="@+id/rl3_List"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@id/rl2_List"
android:layout_alignParentEnd="true"
android:layout_marginStart="100dp">
<ImageView
android:id="@+id/ivList_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="true"
android:src="@drawable/delete_icon"
android:contentDescription="icon to delete item from the Listview"/>
</RelativeLayout>
【问题讨论】:
-
你可以为这堆 tb -- cb -- iv 发布你的 xml 吗?
-
好的,但在 xml 中,我最初将复选框设置为 false
-
由于ListView的回收机制,看这个解释:stackoverflow.com/a/14108676/4224337。在 getView() 方法中,您必须重新检查或重新取消检查 CheckBoxes 取决于它们的状态(选中/未选中)
-
使用 cb.setTag(position)
标签: android listview checkbox android-listview