2012-12-06 22 views
0

我有這樣的微調:共享偏好與微調不維護國家

// Spinner 1 


final Spinner plan = (Spinner) dialog.findViewById(R.id.spinner1); 
strings = getResources().getStringArray(R.array.paymentplan); 
sAdapter = new SpinnerAdapter(this, 
     android.R.layout.simple_spinner_item, strings); 
sAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
plan.setAdapter(sAdapter); 

// plan.setAdapter(spinner1Adapter); 
plan.setSelection(prefsDisplay.getInt("spinnerSelection1", 0)); 
plan.setOnItemSelectedListener(new MyOnItemSelectedListenerPlan()); 

當用戶點擊,我希望它來保存狀態:

public void onClick(View v) { 
       Editor editor2 = prefsPlan.edit(); 
       int selectedPosition1 = plan.getSelectedItemPosition(); 
       editor2.putInt("spinnerSelection1", selectedPosition1); 
       editor2.commit(); 


} 

它保存在SharedPref的位置,但微調器回到默認狀態。有人在這裏看到什麼?

+0

謝謝你,我會檢查出來 – KickingLettuce

回答

1

你存儲spinnerSelection

editor1.putInt("spinnerSelection", selectedPosition); 

的訪問spinnerSelection1

prefsDisplay.getInt("spinnerSelection1", 0) 

使它們保持一致。

更新

當您正在訪問plan.getSelectedItemPosition()。那麼微調器是可見的?我覺得不是。

嘗試爲選定的位置放置一個公共變量。並在您的MyOnItemSelectedListenerPlan中更新selected position。然後將該位置存儲在共享首選項中。我想它解決了你的問題。

+0

對不起,我在錯誤的代碼!我改變了它。 – KickingLettuce

+0

你能解決這個問題嗎? –

0

保存到首選項後,你必須設置所選項目的微調進一步使用

int pos = prefsDisplay.getInt("spinnerSelection", "0"); 
display.setSelection(pos); 

,但使用的是spinnerSelection1。所以默認情況下,如果在首選項中沒有匹配。默認值將返回。所以這裏返回並微調器設置爲第一位置

+0

但我在這裏設置:'plan.setSelection(prefsDisplay.getInt(「spinnerSelection1」,0));' – KickingLettuce

+0

此外,我改變了我的代碼,我有錯誤的代碼。 spinnerSelection是一致的。 – KickingLettuce

+0

嘗試在logcat中設置爲微調器時打印「spinnerSelection1」 –

1

保存:

int selectedPosition = yourSpinner.getSelectedItemPosition() 
editor.putInt("spinnerSelection", selectedPosition); 
editor.commit(); 

加載:

yourSpinner.setSelection(prefs.getInt("spinnerSelection",0)); 

如果你是數組使用它應該像這樣改變

String selectedString = yourArray[yourSpinner.getSelectedItemPosition()]; 
editor.putString("spinnerSelection", selectedString); 
editor.commit(); 

通過調用

ArrayList.indexOf(prefs.getString("spinnerSelection", ""); 

當您檢查數組[我]針對存儲在prefs.if您使用 的ArrayList代替這部分可以在沒有環來實現價值提交顯示所有上面的數組項沒了。沒有人進入 陣列。

1

以下代碼嘗試和第一使用以下代碼並存儲在此之後變量值到共享偏好保存當前選擇的項目的位置成一個整數變量上onItemSelectedListener()

用於將值存儲到一個變量中。

int index; 

public void onItemSelected(AdapterView<?> parent, View v, int position, long id) { 
    // Here Position is Item Index 
    index = position; 
} 

用於將值存儲到共享首選項中。

SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE); 
SharedPreferences.Editor prefsEditor = myPrefs.edit(); 
prefsEditor.putInt("SelectedIndex", index); 
prefsEditor.commit(); 

,看看下面的鏈接瞭解更多信息

Android Spinners

Android Shared Preferences