当您使用复选框滚动列表视图时,项目的位置将发生变化,以便选中的项目可能未选中,未选中的项目可能已选中。因此,为什么所选列表项目无法正确显示。(您是否观察到此问题??)解决这个问题你必须使用 ArrayAdapter 而不是 baseAdapter。
请按照此链接解决问题。
而不是 PlanetsActivity 类使用这个类,剩下的是一样的......
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;
}}