0

我怎样才能使这个代码修剪下来?

    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

2 回答 2

3

以下内容与您的代码完全相同。使用分配给共享首选项的值,如果为空,则分配 0 并同时分配 DP。

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";
}
于 2012-12-06T03:29:25.583 回答
1

使用switchandcase来定义各自的 if 语句,default如果它不匹配任何 if 语句,则使用来分配。

例子:

   int month = 8;
    String monthString;
    switch (month) {
        case 1:  monthString = "January";
                 break;
        case 2:  monthString = "February";
                 break;
        case 3:  monthString = "March";
                 break;
        case 4:  monthString = "April";
                 break;
        case 5:  monthString = "May";
                 break;
        case 6:  monthString = "June";
                 break;
        case 7:  monthString = "July";
                 break;
        case 8:  monthString = "August";
                 break;
        case 9:  monthString = "September";
                 break;
        case 10: monthString = "October";
                 break;
        case 11: monthString = "November";
                 break;
        case 12: monthString = "December";
                 break;
        default: monthString = "Invalid month";
                 break;
    }
    System.out.println(monthString);
于 2012-12-06T03:29:05.223 回答