When you scroll the listview with checkboxes then the position of the items will change so that checked items may unchecked and unchecked items may checked.so that why the selected list items are not displayed properly.(Did you observe this issue??)
to resolve this issue you have to use ArrayAdapter instead of baseAdapter.
Please follow this link to over come the issue.
instead of PlanetsActivity class use this class remaining is same...
public class PlanetsActivity extends Activity {
private ListView mainListView;
//private Planet[] planets;
ArrayList<Planet> planets=new ArrayList<Planet>();
private ArrayAdapter<Planet> listAdapter;
/** Called when the activity is first created. */
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the ListView resource.
mainListView = (ListView) findViewById(R.id.listView1);
// When item is tapped, toggle checked properties of CheckBox and
// Planet.
mainListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
Planet planet = listAdapter.getItem(position);
planet.toggleChecked();
PlanetViewHolder viewHolder = (PlanetViewHolder) item
.getTag();
viewHolder.getCheckBox().setChecked(planet.isChecked());
}
});
Button bt=(Button)findViewById(R.id.yourbutton);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
planets.clear();
for(int i=1;i<15;i++){
planets.add(new Planet(""+i,true));
}
listAdapter = new PlanetArrayAdapter(this, planets);
mainListView.setAdapter(listAdapter);
}
});
planets.add(new Planet("1", false));
planets.add(new Planet("2", false));
planets.add(new Planet("3", false));
planets.add(new Planet("4", false));
planets.add(new Planet("5", false));
planets.add(new Planet("6", false));
planets.add(new Planet("7", false));
planets.add(new Planet("8", false));
planets.add(new Planet("9", false));
planets.add(new Planet("10", false));
planets.add(new Planet("11", false));
planets.add(new Planet("12", false));
planets.add(new Planet("13", false));
planets.add(new Planet("14", false));
listAdapter = new PlanetArrayAdapter(this, planets);
mainListView.setAdapter(listAdapter);
}
public Object onRetainNonConfigurationInstance() {
return planets;
}}