关于更新自定义列表视图有很多问题,一个常见问题似乎是ArrrayList为in this answer的参考问题或者未从UI线程调用更新。虽然我没有设法用这些例子解决我的问题。
据我所知,Arraylist(nameScoresList
)正在更新,并且在调用getView
时似乎也会调用适配器中的notifyDatasetChanged
函数。查看代码中不同位置的日志,Arraylist正在使用新值进行更改。
但是,应用程序的屏幕仍然保留原始列表视图,并且不会随着nameScoresList
的更改值而更改。
任何人都可以看到我犯的错误吗?感谢
我的适配器的代码是:
public class ListViewAdapter extends BaseAdapter{
public ArrayList<HashMap<String, String>> list;
Activity activity;
TextView txtFirst;
TextView txtSecond;
public ListViewAdapter(Activity activity, ArrayList<HashMap<String, String>> list){
super();
this.activity=activity;
this.list=list;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=activity.getLayoutInflater();
if(convertView == null){
convertView=inflater.inflate(R.layout.list_row_name_score, null);
txtFirst=(TextView) convertView.findViewById(R.id.name);
txtSecond=(TextView) convertView.findViewById(R.id.score);
}
HashMap<String, String> map=list.get(position);
txtFirst.setText(map.get(FIRST_COLUMN));
txtSecond.setText(map.get(SECOND_COLUMN));
Log.d("CHECK_UPDATE", map.get(SECOND_COLUMN));
return convertView;
}
// Two previous attempts at an update function
//
// public void refreshScores(float[] outputScores) {
// int count = 0;
// for(HashMap<String, String> entry : this.list) {
// entry.put(SECOND_COLUMN, Float.toString(outputScores[count]));
// count += 1;
// }
// this.notifyDataSetChanged();
// }
// public void refreshScores(ArrayList<HashMap<String, String>> nameScoresList) {
// list.clear();
// list.addAll(nameScoresList);
// this.notifyDataSetChanged();
// }
}
这些是我认为与主要活动相关的部分(如果需要,我可以添加更多):
private ArrayList<HashMap<String, String>> nameScoresList = new ArrayList<HashMap<String, String>>();
public class SpeechActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// Put data in nameScoresList;
for (int i=0; i < speakerJson.entrySet().size(); i++){
nameScoresList.add(new HashMap<String, String>());
}
int ID_number;
for (Map.Entry<String, JsonElement> entry : speakerJson.entrySet()) {
speaker = entry.getKey();
ID_number = entry.getValue().getAsInt();
HashMap<String,String> temp=new HashMap<String, String>();
temp.put(FIRST_COLUMN, speaker.replace("_", " "));
temp.put(SECOND_COLUMN, Float.toString(0));
nameScoresList.set(ID_number - 1, temp);
}
adapter = new ListViewAdapter(this, nameScoresList);
nameScoresLV.setAdapter(adapter);
record();
}
private void record() {
// Get outputScores
// Update Arraylist which ListView uses
int count = 0;
for (HashMap<String, String> entry : nameScoresList) {
entry.put(SECOND_COLUMN, Float.toString(outputScores[count]));
count += 1;
}
runOnUiThread(
new Runnable() {
@Override
public void run() {
adapter.notifyDataSetChanged();
// These are calls which correspond to the commented functions in ListViewAdapter class
//adapter.refreshScores(outputScores);
//adapter.refreshScores(nameScoresList);
}
});
}