Spinner的getSelectedItemPosition()方法返回意外结果

时间:2013-02-13 00:35:49

标签: android spinner

我的应用有一个微调器,里面有四个条目。我需要能够检索选择了哪些标签,而不是实际标签本身。以下是我执行此操作的部分代码:

// Set up the activity's Spinner
    spinnerAdapter = ArrayAdapter.createFromResource(this, R.array.pay_periods, android.R.layout.simple_spinner_item);
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    Spinner s = (Spinner) findViewById(R.id.main_spinner_payperiod);
    s.setAdapter(spinnerAdapter);

在后来的方法中:

switch(payPeriod.getSelectedItemPosition()){
    case(0): // Daily
        dailyAllowance = Float.parseFloat(payment.getText().toString());
    case(1): // Weekly
        dailyAllowance = (Float.parseFloat(payment.getText().toString())) / 7;
    case(2): // Bi-weekly
        dailyAllowance = (Float.parseFloat(payment.getText().toString())) / 14;
    case(3): // 30 days
        dailyAllowance = (Float.parseFloat(payment.getText().toString())) / 30;
    case(Spinner.INVALID_POSITION):
        dailyAllowance = 0;
    default:
        dailyAllowance = 42;    // Junk value, for debugging purposes
    }

无论我选择哪个Spinner项目,此方法似乎总是返回42。任何人都可以帮我找出原因吗?谢谢!

1 个答案:

答案 0 :(得分:5)

break放入开关案例

switch(payPeriod.getSelectedItemPosition()) { 

    case(0): // Daily
        dailyAllowance = Float.parseFloat(payment.getText().toString());
    break;

    case(1): // Weekly
        dailyAllowance = (Float.parseFloat(payment.getText().toString())) / 7;
    break;

    case(2): // Bi-weekly
        dailyAllowance = (Float.parseFloat(payment.getText().toString())) / 14;
    break;

    case(3): // 30 days
        dailyAllowance = (Float.parseFloat(payment.getText().toString())) / 30;
    break;

    case(Spinner.INVALID_POSITION):
        dailyAllowance = 0;
    break;
    default:
        dailyAllowance = 42;    // Junk value, for debugging purposes
    break;
}

在switch-case条件中省略break可能会导致错误的行为。如果选择了case(没有break),则流程仍会继续,并且始终会执行default条件。