滾動時與複選框列表視圖,則項目的位置將發生變化,這樣檢查的項目可以選中和未被檢查的項目可能checked.so,之所以正確,不顯示所選的列表項。(你有沒有觀察到這種問題??) 要解決此問題,您必須使用ArrayAdapter而不是baseAdapter。 Please follow this link to over come the issue.
代替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;
}}