for_2012 2012-12-06 07:10 采纳率: 0%
浏览 2268
已采纳

简化管理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,如果检测到值,就分配,不然就用默认值

  • 写回答

4条回答

  • 寒江独 2012-12-06 09:01
    关注
    s1 = prefsDisplay.getInt("spinnerSelection", -1 );
    if( s1 != 0 && s1 != 1 && s1 != 2 && s1 != 3) { 
        s1 = 0;
        DP.BreakdownMonths = 0;
    }
    

    这样应该和最初的代码意思一致。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?