如果语法在这里关闭,我深表歉意,尤其是关于布尔值:
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;
}
}
}
根据用户是否选择任一布尔类型,应执行不同的计算,但只有转换为磅才有效。