1) The first, but also the longest-to-see method of addition (click on the button for example)
Button BTN = (Button) Findviewbyid (R.id.mybutton); btn. Setonclicklistener (new View.onclicklistener () { publicvoid//dosomething } });
2) Second, the following method is slightly simpler than the previous one, allowing multiple buttons to share a single listener. To control the response to different button click events via the switch:
Button BTN =(Button) Findviewbyid (R.id.mybutton); Button btn2=(Button) Findviewbyid (R.id.mybutton2); Btn.setonclicklistener (handler); Btn2.setonclicklistener (handler); View.onclicklistener Handler=View.onclicklistener () { Public voidOnClick (View v) {Switch(V.getid ()) { CaseR.id.mybutton://Do something Break; CaseR.id.mybutton2://Do something Break; } }
Or
Button list=NULL; Button About=NULL; /**Called when the activity is first created.*/@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Requestwindowfeature (Window.feature_no_title); Setcontentview (R.layout.main); List=(Button) Findviewbyid (R.ID.FOODLISTBTN); about=(Button) Findviewbyid (R.id.aboutbutton);//list.settext (text);//List.setcompounddrawables (left, top, right, bottom);List.setonclicklistener ( This); About.setonclicklistener ( This); } @Override Public voidOnClick (View v) {//TODO auto-generated Method Stub if(V.getid () = =r.id.foodlistbtn) {Intent Intent=NewIntent (); Intent.setclass (Mainapp. This, Foodlistview.class); StartActivity (Intent); List.setbackgroundresource (r.drawable.btn_food_list_active); }Else if(V.getid () = =R.id.aboutbutton) {Intent Intent=NewIntent ( This, about.class); StartActivity (Intent); About.setbackgroundresource (r.drawable.btn_food_about_active); } }
3) Third, directly clicklistener bundle the views element in the XML layout, the listener method defined in the program requires a parameter with a view type:
<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "vertical"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"> <TextViewAndroid:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:id= "@+id/text"Android:text= "@string/hello" /> <ButtonAndroid:id= "@+id/mybutton"Android:layout_height= "Wrap_content"Android:layout_width= "Wrap_content"Android:onclick= "Mybuttonlistener"></Button></LinearLayout>
Java code:
Button BTN = (Button) Findviewbyid (R.id.mybutton); Public void //dosomething }
Learn how to add Setonclicklistener from scratch with Android development-view