Original URL: http://www.yrom.net/blog/2011/12/12/android-4-onclicklistener-of-button/
Button control setOnclickListener(View.OnClickListener listener) to receive a listener for a click event
- Customizing a click event Listener class
The way to make it view.onclicklistener onClick(View v)
123)45 |
class MyOnClickListener implements View.OnclickListener{ public void onClick(View v){ ... }}
|
Then register to the button
1 |
btn.setOnclickListener(new MyOnClickListener ());
|
- Take the form of an anonymous inner class
When the listener only applies a button, the above method can be simplified:
12 345 |
btn.< Span class= "NA" >setonclicklistener (new view.< Span class= "NA" >onclicklistener () { public void onclick (view v) { } |
- The current activity to implement View.onclicklistener
Implement its methods in the activity onClick() . This enables multiple buttons to re-use a listener.
When registering for monitoring, simply give the current object (this) to the button:
1 |
btn.setOnclickListener(this);
|
Tips: use Switch-case for each button's ID to respond accordingly: eg.
123456789 |
PublicvoidOnClick(ViewV){ Switch(V.GetId()){ CaseR.id.:login (); break; case r. Id.: regist (), Span class= "K" >break; default: dosomething (); break; }} /span>
|
- To explicitly specify the OnClick property of a button in a layout file
The layout file corresponding to the activity is added to the form:
123)45 |
<Button android:onClick="click" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/btn_text" />
|
This will invoke the method in the corresponding activity using reflection when the button is clicked click() :
123 |
public void click(View v){...}
|
a button can have only one OnClick property value, and a click () method can be assigned to multiple buttons. you can respond to the button's ID in the click () method, see tips above.
4 ways to respond to click events for Android-button (buttons)