android listview會重復(fù)顯示的問題前面也碰到過這個問題,不過后來解決了,但是沒有留意解決的根本,今天網(wǎng)上搜索了一下,發(fā)現(xiàn)很多人碰到了同樣的問題,不過很多人也沒有找到問題的本質(zhì)所在 public View getView(int position, View convertView, ViewGroup parent) { if(convertView==null){ LinearLayout ll = new LinearLayout(this.context); CheckBox radioButton = new CheckBox(this.context); radioButton.setPadding(0, 0, 0, 0); final String key = this.keys[position]; radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(!isChecked){ datas.put(key, false); }else{ datas.put(key, true); } } }); if(!datas.get(key)){ radioButton.setChecked(false); }else{ radioButton.setChecked(true); }
TextView tv = new TextView(this.context); tv.setText(this.attributes.get(key)+key+position); tv.setGravity(Gravity.RIGHT); tv.setPadding(0, 0, 10, 0); tv.setTextColor(Color.BLACK);
ll.setGravity(Gravity.RIGHT); ll.setPadding(5, 5, 10, 5); ll.addView(tv); ll.addView(radioButton); return ll; } return convertView; } 其實產(chǎn)生的原因在于android的listview對顯示做了優(yōu)化,也就是在內(nèi)存中只保存顯示數(shù)量(listview當前能夠顯示的行數(shù),有誤差,因為有些只顯示半行),對于如果用上面的方法,就會產(chǎn)生一個循環(huán)顯示,其實如果你不需要保存每行的數(shù)據(jù),完全可以把convertView==nul這個條件去掉,因為系統(tǒng)已經(jīng)幫我們做了優(yōu)化,當然如果你想對每行做記錄,那就只能改成以下的方式 : @Override public View getView(int position, View convertView, ViewGroup parent) { if(this.rows[position]==null){ LinearLayout ll = new LinearLayout(this.context); CheckBox radioButton = new CheckBox(this.context); radioButton.setPadding(0, 0, 0, 0); final String key = this.keys[position]; radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(!isChecked){ datas.put(key, false); }else{ datas.put(key, true); } } }); if(!datas.get(key)){ radioButton.setChecked(false); }else{ radioButton.setChecked(true); }
TextView tv = new TextView(this.context); tv.setText(this.attributes.get(key)+key+position); tv.setGravity(Gravity.RIGHT); tv.setPadding(0, 0, 10, 0); tv.setTextColor(Color.BLACK);
ll.setGravity(Gravity.RIGHT); ll.setPadding(5, 5, 10, 5); ll.addView(tv); ll.addView(radioButton); this.rows[position] = ll; return ll; } return this.rows[position]; } |
|