你好,游客 登录 注册 搜索
背景:
阅读新闻

Android简单控件使用--计算BMI的例子

[日期:2011-10-30] 来源:Linux社区  作者:cool_android [字体:大 中 小]

对于Button控件,若要为其click事件添加响应函数,可以在Activity中这样做:

1. 让Activity实现OnClickListener这个接口

2. 为Button设置click listener

btn.setOnClickListener(this);

3. 在onClick函数中添加相应的操作

  1. public void onClick(View v)   
  2. {  
  3.     switch(v.getId())  
  4.     {  
  5.          case R.id.button_OK:  
  6.          break:  
  7.      }  
  8. }  

完整的Activity的代码如下:

  1. public class BMI extends Activity implements OnClickListener {  
  2.     /** Called when the activity is first created. */  
  3.     private EditText edit_height;  
  4.     private RadioButton radiobutton_Man, radiobutton_Woman;  
  5.     private Button btn = null;  
  6.       
  7.     @Override  
  8.     public void onCreate(Bundle savedInstanceState)   
  9.     {  
  10.         super.onCreate(savedInstanceState);  
  11.         setContentView(R.layout.main);  
  12.           
  13.         edit_height = (EditText) findViewById(R.id.height_Edit);  
  14.         radiobutton_Man = (RadioButton) findViewById(R.id.Sex_Man);  
  15.         radiobutton_Woman = (RadioButton) findViewById(R.id.Sex_Woman);  
  16.           
  17.         btn = (Button) findViewById(R.id.button_OK);  
  18.         btn.setOnClickListener(this);  
  19.           
  20.     }  
  21.       
  22.     public void onClick(View v)   
  23.     {  
  24.         // TODO Auto-generated method stub   
  25.         switch(v.getId())  
  26.         {  
  27.             case R.id.button_OK:  
  28.                 try   
  29.                 {  
  30.                     /* 取得输入的身高*/  
  31.                     double height = Double.parseDouble (edit_height.getText().toString());  
  32.                     /* 取得选择的性别*/  
  33.                     String sex = "";  
  34.                     if (radiobutton_Man.isChecked())   
  35.                     {  
  36.                         sex = "M";  
  37.                     } else   
  38.                     {  
  39.                         sex = "F";  
  40.                     }  
  41.                       
  42.                       
  43.                 }   
  44.                 catch (Exception e)   
  45.                 {  
  46.                     // TODO: handle exception   
  47.                     Toast.makeText(this,"error", Toast.LENGTH_LONG).show();  
  48.                 }  
  49.                 break;  
  50.         }  
  51.               
  52.     }  
  53. }  
linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款