讀取 SharedPreferences 時,常見寫法是多層 if-else 判斷數值並指派預設值,實際上可大幅簡化。
if (prefsDisplay.getInt("spinnerSelection", 0) == 0) { s1 = 0; }
else if (prefsDisplay.getInt("spinnerSelection", 0) == 1) { s1 = 1; }
else if (prefsDisplay.getInt("spinnerSelection", 0) == 2) { s1 = 2; }
else if (prefsDisplay.getInt("spinnerSelection", 0) == 3) { s1 = 3; }
else { s1 = 0; DP.BreakdownMonths = 0; }
s1 = prefsDisplay.getInt("spinnerSelection", -1);
if (s1 != 0 && s1 != 1 && s1 != 2 && s1 != 3) {
s1 = 0;
DP.BreakdownMonths = 0;
}
getInt(key, defaultValue) 若鍵不存在會回傳預設值(此處用 -1 做哨兵值)。spinnerSelection1 等其他偏好設定。此寫法減少重複呼叫 getInt(),提升可讀度與效能。