(1)匿名内部类
public class TestButtonActivity extends Activity {
Button btn1, btn2;
Toast tst;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_button);
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast tst = Toast.makeText(TestButtonActivity.this, "111111111", Toast.LENGTH_SHORT);
tst.show();
}
});
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast tst = Toast.makeText(TestButtonActivity.this, "222222222", Toast.LENGTH_SHORT);
tst.show();
}
});
}
}
(2)自定义单击事件监听类
public class TestButtonActivity extends Activity {
Button btn1, btn2;
Toast tst;
class MyClickListener implements OnClickListener {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
tst = Toast.makeText(TestButtonActivity.this, "111111111", Toast.LENGTH_SHORT);
tst.show();
break;
case R.id.button2:
tst = Toast.makeText(TestButtonActivity.this, "222222222", Toast.LENGTH_SHORT);
tst.show();
break;
default:
break;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_button);
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
btn1.setOnClickListener(new MyClickListener());
btn2.setOnClickListener(new MyClickListener());
}
}
(3)Activity继承View.OnClickListener,由Activity实现OnClick(View view)方法,在OnClick(View view)方法中用switch-case对不同id代表的button进行相应的处理
public class TestButtonActivity extends Activity implements OnClickListener {
Button btn1, btn2;
Toast tst;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_button);
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
tst = Toast.makeText(this, "111111111", Toast.LENGTH_SHORT);
tst.show();
break;
case R.id.button2:
tst = Toast.makeText(this, "222222222", Toast.LENGTH_SHORT);
tst.show();
break;
default:
break;
}
}
}