我在Android中創建了一個ListView
的適配器,它的行爲真的很奇怪。該列表視圖傳遞了一個對象列表,它按照一些規則排序(比較數字,哇...)。現在,當列表顯示在視圖中時,會顯示重複的條目,它們不會排序,條目丟失,並且當我滾動列表時甚至條目也會更改!到底是怎麼回事?爲什麼我的列表視圖在android中表現奇怪?
這裏是適配器的代碼,我可以張貼更多的代碼,如果這是必要的:
public class StatViewAdapter extends BaseAdapter {
Activity activity;
ArrayList<Entry> entries;
TextView txtName;
TextView txtOK;
TextView txtNOK;
TextView txtHist;
TextView txtPrandom;
TextView txtPhist;
TextView txtPtotal;
//public StatViewAdapter(Activity activity, ArrayList<HashMap<String, String>> list){
public StatViewAdapter(Activity activity, ArrayList<Entry> entries){
super();
this.activity=activity;
this.entries = entries;
Collections.sort(this.entries, new Comparator<Entry>() {
@Override
public int compare(Entry o1, Entry o2) {
if (o1.getPriority() > o2.getPriority()) {
return 1;
}
if (o1.getPriority() < o2.getPriority()) {
return -1;
}
return 0;
}
});
for (int i=0;i<this.entries.size();i++) {
String name = this.entries.get(i).name();
int p = this.entries.get(i).getPriority();
System.out.println(String.format("%s: %d", name, p));
}
}
@Override
public int getCount() {
// TODO Auto-generated method stub
//return list.size();
return this.entries.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return this.entries.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater=this.activity.getLayoutInflater();
if(convertView == null){
convertView=inflater.inflate(R.layout.list_view, null);
txtName=(TextView) convertView.findViewById(R.id.listname);
txtOK=(TextView) convertView.findViewById(R.id.listok);
txtNOK=(TextView) convertView.findViewById(R.id.listnok);
txtHist=(TextView) convertView.findViewById(R.id.listhist);
txtPrandom =(TextView) convertView.findViewById(R.id.listprandom);
txtPhist=(TextView) convertView.findViewById(R.id.listphist);
txtPtotal=(TextView) convertView.findViewById(R.id.listptot);
}
Entry entry = this.entries.get(position);
txtName.setText(entry.name());
txtOK.setText(Integer.toString(entry.number_ok));
txtNOK.setText(Integer.toString(entry.number_nok));
txtHist.setText(entry.history);
txtPrandom.setText(Integer.toString(entry.randomIndex));
txtPhist.setText(Integer.toString(entry.histIndex));
txtPtotal.setText(Integer.toString(entry.getPriority()));
return convertView;
}
}
很明顯,因爲您在適配器 – Selvin
中直接存儲對項目視圖的引用,什麼?你可以解釋嗎?它對我來說並不明顯... – Alex
分析如果convertView不爲null,但與getView返回的最後一個視圖不一樣會發生什麼 – Selvin