我有一個Android應用程序,它使用ListView顯示列表,並且有一個操作欄按鈕來清除所述列表。我決定添加一個確認對話框,以便人們不會意外刪除所有條目,並且遇到問題。如果我在onclick中使用setListAdapter作爲對話框中的「yes」按鈕,它將不會編譯。如果我在onclick之外使用它,它會起作用,但不會刷新列表,直到用戶退出活動並返回到活動中爲止,這顯然是不合適的。這是我按下「清除列表」操作欄按鈕時調用的方法,其中包含內部按鈕的相關onclick。 我有一種感覺,我不應該在setListAdapter中使用「this」,因爲在對話框中,這不再對應於我認爲的listview活動?但我不確定應該放什麼。如何在onclick中刷新listadapter
public void clearTrigger(MenuItem item) {
//Set up a dialog with two buttons to verify that the user really wants to delete
everything
confirm = new Dialog(display.this);
confirm.setContentView(R.layout.conf);
confirm.setTitle("Confirm deletion");
yes = (Button)confirm.findViewById(R.id.yes);
//If the user says yes, then delete everything
yes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Remove everything from Hours.
Hours.clear();
String tempH = " ";
String tempW = " ";
//Then save it again in it's new, empty state so that it doesn't reappear the next time the app is run.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor edit = prefs.edit();
edit.putString("SAVEDATA", TextUtils.join(",", Hours));
edit.remove("totalh");
edit.remove("totalw");
edit.commit();
//And finally... refresh the list view - doesn't work
setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_list, R.id.listText, Hours));
confirm.dismiss();
}
});
confirm.show();
}
使用listview的notifydatachanged()而不是再次設置setlistadapter –