对于Button控件,若要为其click事件添加响应函数,可以在Activity中这样做:
1. 让Activity实现OnClickListener这个接口
2. 为Button设置click listener
btn.setOnClickListener(this);
3. 在onClick函数中添加相应的操作
- public void onClick(View v)
- {
- switch(v.getId())
- {
- case R.id.button_OK:
- break:
- }
- }
完整的Activity的代码如下:
- public class BMI extends Activity implements OnClickListener {
- /** Called when the activity is first created. */
- private EditText edit_height;
- private RadioButton radiobutton_Man, radiobutton_Woman;
- private Button btn = null;
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- edit_height = (EditText) findViewById(R.id.height_Edit);
- radiobutton_Man = (RadioButton) findViewById(R.id.Sex_Man);
- radiobutton_Woman = (RadioButton) findViewById(R.id.Sex_Woman);
- btn = (Button) findViewById(R.id.button_OK);
- btn.setOnClickListener(this);
- }
- public void onClick(View v)
- {
- // TODO Auto-generated method stub
- switch(v.getId())
- {
- case R.id.button_OK:
- try
- {
- /* 取得输入的身高*/
- double height = Double.parseDouble (edit_height.getText().toString());
- /* 取得选择的性别*/
- String sex = "";
- if (radiobutton_Man.isChecked())
- {
- sex = "M";
- } else
- {
- sex = "F";
- }
- }
- catch (Exception e)
- {
- // TODO: handle exception
- Toast.makeText(this,"error", Toast.LENGTH_LONG).show();
- }
- break;
- }
- }
- }
