我在使用自定义适配器刷新列表视图时遇到了很多麻烦。过去一个小时我一直在网上搜索,但似乎找不到任何可以让我的列表视图刷新的解决方案。
我试过 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);