1. In the parameters directly new a Onclicklistener
Button button1=(Button) findViewById(R.id.button1);//事件源 button1.setOnClickListener(new OnClickListener(){ @Override //findViewById得到的是一个View对象 publicvoidonClick(View v) { // TODO Auto-generated method stub Toast.makeText(FirstActivity.this"haha", Toast.LENGTH_SHORT).show(); } });
2. Multiple buttons share a 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 (NewMyListener ()); Button2.setonclicklistener (NewMyListener ()); }//Build a listener class Public class MyListener implements Onclicklistener{ Public void OnClick(View v) {Switch(V.getid ()) { CaseR.id.button1:toast.maketext (firstactivity. This,"Button1", Toast.length_short). Show (); Break; CaseR.id.button2:toast.maketext (firstactivity. This,"Button2", Toast.length_short). Show (); Break; } } }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Notes (iii) adding events for buttons