1.在参数中直接new一个OnClickListener
Button button1=(Button) findViewById(R.id.button1);//事件源
button1.setOnClickListener(new OnClickListener(){
@Override
//findViewById得到的是一个View对象
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(FirstActivity.this, "haha", Toast.LENGTH_SHORT).show();
}
});
2.多个button共享一个Listener
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.first_layout);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(new mylistener());
button2.setOnClickListener(new mylistener());
}
//建一个监听器类
public class mylistener implements OnClickListener{
public void onClick(View v){
switch(v.getId()){
case R.id.button1:Toast.makeText(FirstActivity.this, "button1", Toast.LENGTH_SHORT).show();
break;
case R.id.button2:Toast.makeText(FirstActivity.this, "button2", Toast.LENGTH_SHORT).show();
break;
}
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/tomi_en/article/details/47785137