Android basics-four writing methods for click events and four writing methods for android
1. Define the internal class to implement click events. When used, pass the internal class object to the setOnClickListener () method of the event source.
Private class MyClickListener implements View. OnClickListener {@ Override public void onClick (View v) {// Function Code }}
2. Click events using anonymous internal classes
SetOnClickListener (new View. OnClickListener () {@ Override public void onClick (View v) {// Function Code }});
3. in the binding click event, the current Activity object is passed in. setOnClickListener (this). this indicates the reference of the Activity object where the current control is located. In this way, View is implemented for the current Activity. onClickListener interface, in The onClick method, determine the operation to be executed by judging the Id of the event source (control.
public class MainActivity extends ActionBarActivity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button but = (Button)this.findViewById(R.id.bt_dial);
But. setOnClickListener (this) ;}@ Override public void onClick (View v) {switch (v. getId () {case R. id. but: // Function Code break; default: break ;}}}
4. Bind The onclick event to the event source in the Activity layout file, and provide event implementation in the Activity
In activity_xxx_xml, add android: onClick = "buttonClicked". buttonClicked indicates the implementation of the click event.
<Button android: onClick = "buttonClicked" android: id = "@ + id/butl" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "button"/>
Add the following code to the Activity. java file. Note that the access permission for click events must be public and the parameter type is View.
Public void buttonClicked (View v) {if (v. getId () = R. id. but) {// Function Code }}