Android计算标准BMI值
今天做了关于计算标准BMI值的小作业,可以计算出你的体重是正常,偏瘦或偏胖
MainAcitivity.java
1 package com.example.bmi; 2 3 import java.text.DecimalFormat; 4 5 import android.support.v7.app.ActionBarActivity; 6 import android.os.Bundle; 7 import android.view.Menu; 8 import android.view.MenuItem; 9 import android.view.View; 10 import android.view.View.OnClickListener; 11 import android.widget.Button; 12 import android.widget.EditText; 13 import android.widget.TextView; 14 15 16 public class MainActivity extends ActionBarActivity { 17 18 @Override 19 protected void onCreate(Bundle savedInstanceState) { 20 super.onCreate(savedInstanceState); 21 setContentView(R.layout.activity_main); 22 Button button=(Button) findViewById(R.id.submit); 23 button.setOnClickListener(calcBMI);//按钮点击监听 24 } 25 26 private OnClickListener calcBMI = new OnClickListener() { 27 public void onClick(View v) { 28 DecimalFormat nf = new DecimalFormat("0.00"); //DecimalFormat用于格式化十进制数字 29 EditText fieldheight = (EditText) findViewById(R.id.height); EditText fieldweight = (EditText) findViewById(R.id.weight); 30 double height = Double //Double.parseDouble()是把括号里面内容变成double类型的 31 .parseDouble(fieldheight.getText().toString()) / 100; 32 double weight = Double 33 .parseDouble(fieldweight.getText().toString()); 34 double BMI = weight / (height * height); 35 TextView result = (TextView) findViewById(R.id.result); 36 result.setText("Your BMI is " + nf.format(BMI)); 37 // Give health advice 38 TextView fieldsuggest = (TextView) findViewById(R.id.suggest); 39 if (BMI > 25) { 40 fieldsuggest.setText("多吃点" ); 41 42 } else if (BMI < 20) { 43 fieldsuggest.setText("正常" ); 44 45 } else { 46 result.setText("该减肥了" ); } 47 48 49 50 } 51 }; 52 }
activity_main.xml
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="身高(cm)" /> <EditText android:id="@+id/height" android:layout_width="fill_parent" android:layout_height="wrap_content" android:numeric="integer" android:text="" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="体重(kg)" /> <EditText android:id="@+id/weight" android:layout_width="fill_parent" android:layout_height="wrap_content" android:numeric="integer" android:text="" /> <Button android:id="@+id/submit" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="计算BMI值" /> <TextView android:id="@+id/result" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" /> <TextView android:id="@+id/suggest" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" />