问题描述
- 简化管理SharedPreferences的代码
- 怎么样能缩减一下这些代码?
prefsDisplay = getSharedPreferences(""spinnerSelection"" Context.MODE_PRIVATE); prefsPlan = getSharedPreferences(""spinnerSelection1"" Context.MODE_PRIVATE); 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; } if (prefsPlan.getInt(""spinnerSelection1"" 0) == 0) { s2 = 0; } else if (prefsPlan.getInt(""spinnerSelection1"" 0) == 1) { s2 = 1; } else if (prefsPlan.getInt(""spinnerSelection1"" 0) == 2) { s2 = 2; } else { s2 = 0; DP.PlanType = ""highint""; }
代码的功能是,当应用程序登入,检测
SharedPreferences
,如果检测到值,就分配,不然就用默认值
解决方案
s1 = prefsDisplay.getInt(""spinnerSelection"" -1 );if( s1 != 0 && s1 != 1 && s1 != 2 && s1 != 3) { s1 = 0; DP.BreakdownMonths = 0;}
这样应该和最初的代码意思一致。
解决方案二:
你可以试试这个
s1 = prefsDisplay.getInt(""spinnerSelection"" 0);
解决方案三:
下面代码和你实现功能是一样的:
prefsDisplay = getSharedPreferences(""spinnerSelection"" Context.MODE_PRIVATE);prefsPlan = getSharedPreferences(""spinnerSelection1"" Context.MODE_PRIVATE);s1 = prefsDisplay.getInt(""spinnerSelection"" -1 );if( s1 < 0 ) { s1 = 0; DP.BreakdownMonths = 0;}s2 = prefsPlan.getInt(""spinnerSelection1"" -1 );if( s2 < 0 ) { s2 = 0; DP.PlanType = ""highint"";}
解决方案四:
楼上回答的很好了。。。对于sharepreference,楼主好好看看的它的用法。
时间: 2024-12-04 18:49:19