2012/06/18

2012/06/13

[Android]BMI

package kevin.demo;

import java.math.BigDecimal;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class BMIActivity extends Activity implements OnClickListener
{
private TextView txtResult;
private EditText edtWeight;
private EditText edtHeight;
private Button btnGo;
private TextView txtScale;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        txtResult = (TextView)findViewById(R.id.txtResult);
        txtScale = (TextView)findViewById(R.id.txtScale);
        edtHeight = (EditText)findViewById(R.id.edtHeight);
        edtWeight = (EditText)findViewById(R.id.edtWeight);
        btnGo = (Button)findViewById(R.id.btnGo);
        
        btnGo.setOnClickListener(this);
        
    }

public void onClick(View v) 
{
// TODO Auto-generated method stub
if(v.equals(btnGo))
{
float W,H,BMI;
W = Float.parseFloat(edtWeight.getText().toString());
H = Float.parseFloat(edtHeight.getText().toString());
H = H / 100;
BMI = W / (H*H);
BigDecimal  Get  =  new  BigDecimal(BMI);  
float  Result  =  Get.setScale(2,  BigDecimal.ROUND_HALF_UP).floatValue();  
//四捨五入並保留兩位小數
txtResult.setText("您的BMI: "+Float.toString(Result));
if(BMI < 18.5)
{
//體重過輕
txtScale.setText("體重過輕");
}
else if((BMI >= 18.5)&&(BMI < 24))
{
//正常範圍
txtScale.setText("正常範圍");
}
else if((BMI >= 24)&&(BMI < 27))
{
//過重
txtScale.setText("體重過重");
}
else if((BMI >= 27)&&(BMI < 30))
{
//輕度肥胖
txtScale.setText("輕度肥胖");
}
else if((BMI >= 30)&&(BMI < 35))
{
//中度肥胖
txtScale.setText("中度肥胖");
}
else if(BMI >= 35)
{
//重度肥胖
txtScale.setText("重度肥胖");
}
}
}