這是一個小而完整的入門範例:使用者先選擇性別,再輸入身高,按下按鈕後以 Toast 顯示對應的標準體重。雖然邏輯簡單,卻把單選控制、輸入讀取、條件判斷與數值格式化四件事串了起來。
Activity 中把初始化拆成三個方法:creadView() 取得元件、sexChoose() 判斷性別、setListener() 掛上按鈕監聽,onCreate 依序呼叫,可讀性比全部塞在一起好得多。
public class BMIActivity extends Activity {
private Button countButton;
private EditText heighText;
private RadioButton maleBtn, femaleBtn;
String sex = "";
double height;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
creadView();
sexChoose();
setListener();
}
private void setListener() {
countButton.setOnClickListener(countListner);
}
private OnClickListener countListner = new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(BMIActivity.this,
"你是一位" + sexChoose()
+ "\n你的身高為" + Double.parseDouble(heighText.getText().toString()) + "cm"
+ "\n你的標準體重為" + getWeight(sexChoose(), height) + "kg",
Toast.LENGTH_LONG).show();
}
};
// 性別判斷
private String sexChoose() {
if (maleBtn.isChecked()) {
sex = "男性";
} else if (femaleBtn.isChecked()) {
sex = "女性";
}
return sex;
}
// 取得元件
public void creadView() {
countButton = (Button) findViewById(R.id.btn);
heighText = (EditText) findViewById(R.id.etx);
maleBtn = (RadioButton) findViewById(R.id.male);
femaleBtn = (RadioButton) findViewById(R.id.female);
}
// 小數格式化
private String format(double num) {
NumberFormat formatter = new DecimalFormat("0.00");
return formatter.format(num);
}
// 依性別計算標準體重
private String getWeight(String sex, double height) {
height = Double.parseDouble(heighText.getText().toString());
String weight = "";
if (sex.equals("男性")) {
weight = format((height - 80) * 0.7);
} else {
weight = format((height - 70) * 0.6);
}
return weight;
}
}
main.xml 的 root 是垂直 LinearLayout,背景設為 @drawable/pic,內部由上而下為:標題 TextView、性別提示、一個水平排列的 RadioGroup(含 male「男」與 female「女」)、身高提示、身高輸入框 etx,以及計算按鈕 btn。
android:inputType="number",並在按下按鈕前先攔截空值與非數字輸入,否則 Double.parseDouble 會直接拋出例外。DecimalFormat("0.00") 能把結果固定成兩位小數,比直接顯示浮點數整齊得多。OnCheckedChangeListener 即時更新,不必每次點擊都重新判斷。