[英]dynamic spinner and sharedpreferences
在我的android應用程序中,我有一個Button,它將一個新的動態Spinner添加到布局中。 所有創建的微調框都使用相同的數組。
到現在為止,我可以保存創建的微調器的數量,並在重新啟動應用程序后重新創建它們。 但是我真的很想將每個微調器的selectedPosition保存在sharedPreferences中,這就是我困在ForceClose Desaster中的地方...
以我的理解,每個微調器在創建時都會獲得一個ID,因此您可以在首選項中保存與此ID綁定的排名。
這就是我所做的:
public void addSpinner(){
LinearLayout AddLayout = (LinearLayout)findViewById(R.id.linearAddScroll);
spinner = new Spinner(this);
ArrayAdapter<?> adapt = ArrayAdapter.createFromResource(this,
R.array.Filter, android.R.layout.simple_spinner_item);
adapt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapt);
AddLayout.addView(spinner);
}
這將創建微調框。
public void onClick(View v) {
addSpinner();
int ID = 1000+x;
spinner.setId(ID);
Toast.makeText(MatReporterActivity.this,"ID" + ID, 5)
.show();
x++;
}
設置ID。
這是我在on Create方法中所做的:
x = settings.getInt("xsave", 1);
for(y = 1; y < x; y++){
addSpinner();
int ID = 1000+y;
Spinner s = (Spinner) findViewById(ID);
String ys= Integer.toString(ID);
Toast.makeText(MatReporterActivity.this,"ID" +ys, 5)
.show();
int yf = settings.getInt(ys, 1);
s.setSelection(yf);
}
這onStop():
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("xsave", x);
for(y = 1; y < x; y++){
int ID = 1000+y;
Spinner s2= (Spinner) findViewById(ID);
int possS = s2.getSelectedItemPosition();
Toast.makeText(MatReporterActivity.this, "IDStop" + ID, 5)
.show();
String ys= Integer.toString(ID);
editor.putInt(ys, possS);
}
editor.commit();
}
我認為onCreate方法中存在一個邏輯問題,但我找不到它,也找不到任何有關如何填充和保存動態創建的微調器的幫助。
所以也許有人有一個主意。 謝謝。
SharedPreferences不是存儲此類數據的好方法。 您應該嘗試遵循以下兩個步驟:
創建一個實現Serializable的類,以表示要存儲的數據(您可以使用Serializable對象的列表)
public class SpinnerSave implements Serializable {
public String ID;
public int selection;
public SpinnerSave(String ID, int selection){
this.ID = ID;
this.selection = selection;
}
}
然后,您應該將數據寫入這樣的文件中
private void saveState() {
final File cache_dir = this.getCacheDir();
final File suspend_f = new File(cache_dir.getAbsoluteFile() + File.separator + SUSPEND_FILE);
FileOutputStream fos = null;
ObjectOutputStream oos = null;
boolean keep = true;
try {
fos = new FileOutputStream(suspend_f);
oos = new ObjectOutputStream(fos);
oos.writeObject(this.gameState);
}
catch (Exception e) {
keep = false;
Log.e("MyAppName", "failed to suspend", e);
}
finally {
try {
if (oos != null) oos.close();
if (fos != null) fos.close();
if (keep == false) suspend_f.delete();
}
catch (Exception e) { /* do nothing */ }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.