Android 安卓 案例

package android.demo.study.hehe1;

import java.text.DecimalFormat;

import android.app.Activity;
import android.app.SearchManager.OnCancelListener;
import android.demo.study.hehe1.R;
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 BMI extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 窗体显示
    setContentView(R.layout.main);
    // 根据id获得程序中需要的组件对象
    findViews();
    // 设置事件监听
    setListensers();
  }
   
  private EditText field_height = null;
  private EditText field_weight = null;
  private Button button_calc = null;
  private TextView view_result = null;
     private TextView view_suggest = null;
    
  /*
   * 声明与查找界面组件
   */
  private void findViews() {
    // 获得"身高"这个文本框对象
    field_height = (EditText)findViewById(R.id.height);
    // 获得"体重"这个文本框对象
    field_weight = (EditText)findViewById(R.id.weight);
    // 获得"计算"这个按钮对象
    button_calc = (Button)findViewById(R.id.submit);
    // 获得"结果"这个显示文本对象
    view_result = (TextView)findViewById(R.id.result);
    // 获得"建议"这个显示文本对象
    TextView view_suggest = (TextView)findViewById(R.id.suggest);
  }
    
  /*
   * Listen for button clicks 为特定界面组件添加控制流程
   */
  private void setListensers() {
    button_calc.setOnClickListener(calcBMI);
  }
    
  /*
   * 监听事件 点击
   */
  private OnClickListener calcBMI = new OnClickListener() {
    public void onClick(View view) {
      // 格式化处理
      DecimalFormat df = new DecimalFormat("0.00");
      // 得到"身高"值   cm --> m
      double height = Double.parseDouble(field_height.getText().toString()) / 100;
      // 得到"体重"值
      double weight = Double.parseDouble(field_weight.getText().toString());
      // 计算出"BMI"的值
      double BMIvalue = weight / (height * height);         
      // 设置"结果"这个显示文本对象的值
      view_result.setText("Your BMI is " + df.format(BMIvalue));
      // Give health advice
      TextView fieldsuggest = (TextView)findViewById(R.id.suggest);
      if (BMIvalue > 25.00) {
        fieldsuggest.setText(R.string.advice_heavy);
      } else if (BMIvalue < 20.00) {
        fieldsuggest.setText(R.string.advice_light);
      } else {
        fieldsuggest.setText(R.string.advice_average);
      }
    }
  };
}


 

你可能感兴趣的:(android,null,Class,import,button)