我在使用自定義適配器刷新列表視圖時遇到了很多麻煩。我一直在網上搜索過去的一小時,我似乎無法找到任何解決方案,這將使我的列表視圖刷新。Android ListView適配器不會刷新
我試過notifyDataSetChanged,也listView.invalidate,但似乎沒有工作。任何幫助將不勝感激。我可以看到使用logcat更新的數據,但它並沒有在屏幕上刷新,我不知道爲什麼。
以下是代碼。
ArrayList<Student> students = new ArrayList<Student>();
listview = (ListView) findViewById(R.id.listView);
adapter = new StudentAdapter(this, R.layout.listitemlayout, students);
listview.setAdapter(adapter);
定義適配器
public class StudentAdapter extends ArrayAdapter<Student>{
Context context;
int layoutResourceId;
ArrayList<Student> data = null;
public StudentAdapter(Context context, int layoutResourceId, ArrayList<Student> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
public void updateStudentsList(ArrayList<Student> newlist){
data.clear();
data = newlist;
this.notifyDataSetChanged();
}
public void updateStudentTime(){
for (Student s : data) {
s.updateElapsedTime();
}
this.notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
Student student = data.get(position);
TextView title = (TextView)row.findViewById(R.id.txtTitle);
title.setText(student.getFirstname() + " " + student.getLastname());
TextView subTitle = (TextView)row.findViewById(R.id.txtSubTitle);
subTitle.setText(student.getStudentID());
TextView duration = (TextView)row.findViewById(R.id.textDuration);
duration.setText(student.getElapsedTime());
}
return row;
}
}
我更新使用一個線程,每隔一段時間數據。
Runnable runnable = new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
// Updates how long the student is in the centre.
adapter.updateStudentTime();
adapter.notifyDataSetChanged();
listview.invalidate();
Log.i("Debug", "Running on UI Thread");
}
});
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
更新UI線程。調用adapter.updateStudentTime();使用runonuithread – Raghunandan 2013-05-02 03:45:28