Android点击Button实现功能的几种方法总结

  package com.example.buttonclicktest;

  import android.app.Activity;

  import android.os.Bundle;

  import android.view.Menu;

  import android.view.View;

  import android.view.View.OnClickListener;

  import android.widget.Button;

  public class MainActivity extends Activity implements OnClickListener{

  private Button button1 = null;

  private Button button2 = null;

  public void findButton() {

  button1 = (Button)findViewById(R.id.button1);

  button2 = (Button)findViewById(R.id.button2);

  }

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  findButton();

  button2.setOnClickListener(this);

  button1.setOnClickListener(new OnClickListener() {

  @Override

  public void onClick(View v) {

  // TODO Auto-generated method stub

  System.out.println("您点击了Button1");

  }

  });

  }

  @Override

  public boolean onCreateOptionsMenu(Menu menu) {

  // Inflate the menu; this adds items to the action bar if it is present.

  getMenuInflater().inflate(R.menu.activity_main, menu);

  return true;

  }

  @Override

  public void onClick(View v) {

  // TODO Auto-generated method stub

  switch (v.getId()) {

  case R.id.button2:

  System.out.println("您点击了Button2");

  break;

  default:

  break;

  }

  }

  public void clickHandler(View view) {

  System.out.println("您点击了Button3");

  }

  }