XML文件
<EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="phone" android:ems="10" android:id="@+id/et_number" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/dial_number" android:id="@+id/bt_dial" android:layout_below="@id/et_number" android:layout_alignRight="@id/et_number" android:layout_alignEnd="@id/et_number" />
第一种、匿名内部类:
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(); } }); }
第二种、自定义单击事件监听类:
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(); } }
第三种、Activity继承View.OnClickListener,由Activity实现OnClick(View view)方法,在OnClick(View view)方法中用switch-case对不同id代表的button进行相应的处理:
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; } } }
第四种、在XML文件中显示指定按钮的onClick属性,这样点击按钮时会利用反射的方式调用对应Activity中的click()方法:
<Button android:onClick="dialPhoneMethod" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/dial_number" android:id="@+id/bt_dial" android:layout_below="@id/et_number" android:layout_alignRight="@id/et_number" android:layout_alignEnd="@id/et_number" />
public void dialPhoneMethod(View view){ dialPhone(); } private void dialPhone() { String number = et_number.getText().toString().trim(); if (TextUtils.isEmpty(number)){ Toast.makeText(this, "电话号码不能为空", Toast.LENGTH_LONG).show(); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:" + number)); startActivity(intent); }