0

我想我对这里的活动生命周期感到困惑,我正在尝试执行简单的权重转换,没什么了不起的。

用户输入一个值,选择他们是否希望将其转换为 lbs 或 kgs,当他们按下“Convert”时,它应该吐出转换后的值,查看堆栈跟踪似乎与使用的 parseInt 有问题。

public class WeightConverter extends Activity implements OnClickListener, OnCheckedChangeListener {
Button convertWeight;
TextView conversionResults;
EditText enterWeight;
RadioGroup weightPicker;
RadioButton radKG, radLB;
double weightValue, convertedWeight;
String weightString;
String measurement;


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.weightconverter);
    initializeVariables();
}

private void initializeVariables() {
    convertWeight = (Button) findViewById(R.id.btnConvertWeight);
    conversionResults =(TextView) findViewById(R.id.tvWeightConversion);
    enterWeight =(EditText) findViewById(R.id.etWeightToConvert);
    weightPicker = (RadioGroup) findViewById(R.id.rgWeightType);
    radKG = (RadioButton) findViewById(R.id.radKG);
    radLB = (RadioButton) findViewById(R.id.radLB);
    convertWeight.setOnClickListener(this);


}

@Override
public void onClick(View v) {
    ;
    switch (v.getId()) {

    case R.id.btnConvertWeight:
        weightValue = Double.parseDouble(enterWeight.getText().toString());

        conversionResults.setText(weightValue + " = " + weightString + measurement);
        break;
    }

}

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {

    switch (checkedId) {

    case R.id.radKG:
        convertedWeight = weightValue / 2.2;
        measurement = " Kilograms";
        break;
    case R.id.radLB:

        convertedWeight = weightValue * 2.2;
        measurement = " Pounds";
        break;

    }weightString = String.valueOf(convertedWeight);
}

}

4

2 回答 2

0

您已将 weightValue 声明为 adouble但尝试解析integer

double weightValue,

而是使用

weightValue = Double.parseDouble(enterWeight.getText().toString());

我还建议对您输入的值进行错误检查,以防用户输入非数字

于 2013-05-08T15:08:40.070 回答
0

我根本不相信您的 onCheckedChanged 方法正在被调用(您是否看到使用调试器输入它的代码?)。

尝试将其分配给您的 weightPicker 无线电组,如下所示:

weightPicker.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
    public void onCheckedChanged(RadioGroup group, int checkedId)
    {
        weightValue = Integer.parseInt(enterWeight.getText().toString());
        switch (checkedId) {

        case R.id.radKG:
            convertedWeight = weightValue / 2.2;
            measurement = " Kilograms";
            break;
        case R.id.radLB:

            convertedWeight = weightValue * 2.2;
            measurement = " Pounds";
            break;

    }
});
于 2013-05-08T15:54:51.383 回答