1
我正在開發一個應用程序,該應用程序能夠管理其中有兩個活動的任務。第一項活動是一個簡單的listview,它是一個用戶列表。第二個活動是多選listview,它顯示與該用戶關聯的任務。我設法實現了我的第一個目標,即使用共享首選項來存儲複選框的狀態。我的問題是,當我保存一個用戶的複選框狀態時,當你看到另一個用戶的任務時,這些不再被檢查。 我該如何解決我的問題。共享首選項多項選擇ListView
這是我如何填充列表:
mList = (ListView) findViewById(android.R.id.list);
final DbAdapter db = new DbAdapter(this);
db.open();
data = db.getAllTasks(getIntent().getExtras().get("nameUser").toString());
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,data);
mList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mList.setAdapter(adapter);
這是我選擇用戶的方式,我想顯示的任務:
mList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
final String text = (String) mList.getItemAtPosition(position);
}
});
這也是我用來保存方法使用SharedPreferences的狀態:
private void LoadSelections() {
// if the selections were previously saved load them
SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);
if (settingsActivity.contains(SETTING_DB)) {
String savedItems = settingsActivity
.getString(SETTING_DB, "");
this.selectedItems.addAll(Arrays.asList(savedItems.split(",")));
int count = this.mList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
String currentItem = (String) this.mList.getAdapter()
.getItem(i);
if (this.selectedItems.contains(currentItem)) {
this.mList.setItemChecked(i, true);
}
}
}
}
private void SaveSelections() {
// save the selections in the shared preference in private mode for the user
SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settingsActivity.edit();
String savedItems = getSavedItems();
prefEditor.putString(SETTING_DB , savedItems);
prefEditor.commit();
}
private String getSavedItems() {
String savedItems = "";
int count = this.mList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (this.mList.isItemChecked(i)) {
if (savedItems.length() > 0) {
savedItems += "," + this.mList.getItemAtPosition(i);
} else {
savedItems += this.mList.getItemAtPosition(i);
}
}
}
return savedItems;
}
我的問候。
嗨。我只是添加了一些代碼來更好地解釋我做了什麼。 – unnamed