I would use the built-in listview function for marking items checked: setItemChecked, combined with a custom checkable view for the rows. For an excellent walkthrough on creating a checkable view (with a section on handling checkbox children) see Here. For completeness, here is an example of a checkable view:
public class ExampleListItemView extends RelativeLayout implements Checkable {
private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };
public ExampleListItemView(Context context) {
super(context);
}
public ExampleListItemView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ExampleListItemView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
TextView txtExample;
CheckBox cbExample;
private boolean isChecked = false;
@Override
protected void onFinishInflate() {
super.onFinishInflate();
txtExample = (TextView) findViewById(R.id.txtExample);
cbExample = (CheckBox) findViewById(R.id.cbExample);
isChecked = false;
}
public void setText(String text){
txtExample.setText(text);
}
@Override
public boolean isChecked() {
return isChecked;
}
@Override
public void setChecked(boolean checked) {
if (isChecked != checked) {
cbExample.setChecked(checked);
isChecked = checked;
refreshDrawableState();
}
}
@Override
public void toggle() {
setChecked(!isChecked);
}
@Override
public int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
}
return drawableState;
}
And the associated xml layout:
<?xml version="1.0" encoding="utf-8"?>
<com.example.ExampleListItemView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
ndroid:addStatesFromChildren="true" >
<CheckBox android:id="@+id/cbExample" />
<TextView
android:id="@+id/txtExample"
android:layout_toRightOf="@id/cbExample" />
</com.example.ExampleListItemView>
You would then end up with something like this:
for(int i = 0; i < adapter.getCount(); i++){
listView.setItemChecked(i, true);
}
SparseBooleanArray checked = listView.getCheckedItemPositions();