Android onClick buttons
Here, four onClick events are used to implement the DEMO of the telephone dial-up device.
XML file
First, anonymous internal class:
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button bt_dial = (Button) findViewById(R.id.bt_dial); bt_dial.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialPhone(); } });}
Second, custom click event listening class:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_number = (EditText) MainActivity.this.findViewById(R.id.et_number); Button bt_dial = (Button) findViewById(R.id.bt_dial); bt_dial.setOnClickListener(new MyListener()); }private class MyListener implements View.OnClickListener { @Override public void onClick(View view) { dialPhone(); } }
Third, the Activity inherits the View. onClickListener: The OnClick (View view) method is implemented by the Activity. In The OnClick (View view) method, switch-case is used to process the buttons represented by different IDs:
public class MainActivity extends Activity implements View.OnClickListener { EditText et_number; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_number = (EditText) MainActivity.this.findViewById(R.id.et_number); Button bt_dial = (Button) findViewById(R.id.bt_dial); bt_dial.setOnClickListener(this); } public void onClick(View view) { switch (view.getId()){ case R.id.bt_dial: dialPhone(); break; default: break; } }}
Fourth, the onClick attribute of the specified button is displayed in the XML file. When you click the button, the click () method in the corresponding Activity is called Using Reflection:
Public void dialPhoneMethod (View view) {dialPhone ();} private void dialPhone () {String number = et_number.getText (). toString (). trim (); if (TextUtils. isEmpty (number) {Toast. makeText (this, the phone number cannot be blank, Toast. LENGTH_LONG ). show (); return;} Intent intent = new Intent (); intent. setAction (Intent. ACTION_CALL); intent. setData (Uri. parse (tel: + number); startActivity (intent );}
Summary:
The fourth method is to implement the Click Event of a button without declaring the button in the entire code. However, this method is not recommended. The third method is the best onClick method. When there are few buttons, using an anonymous internal class will be faster, such as when writing a demo test.