Android使用布尔标志来定义用户输入



如果这里语法错误,我很抱歉,特别是关于布尔值:

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;
    Boolean weightSwitch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weightconverter);
        initializeVariables();
        weightSwitch = false;
        radKG.setChecked(true);
    }
    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);
        weightPicker.setOnCheckedChangeListener(this);

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btnConvertWeight:
            if (weightSwitch = true){
                convertedWeight = weightValue /2.2;
                measurement = "Kilograms";
            }else{
                convertedWeight = weightValue *2.2;
                measurement = "Pounds";
            }

            conversionResults.setText(weightValue + " = " + String.valueOf(convertedWeight) + " " + measurement);
            break;
        }
    }
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        weightValue = Double.parseDouble(enterWeight.getText().toString());
        switch (checkedId) {
        case R.id.radKG:
            weightSwitch = true;
            break;
        case R.id.radLB:
            weightSwitch = false;
            break;
        }
    }

}

根据用户是否选择布尔类型中的任何一种,应该执行不同的计算,但是只将其转换为英镑。

您正在尝试将boolean值与本行中的=运算符进行比较:

if (weightSwitch = true){

=是赋值运算符,所以weightSwitch总是true

使用==来比较boolean的值,或者更好:

if (weightSwitch)

因为它已经是boolean值了

相关内容

  • 没有找到相关文章

最新更新