这里以点击按钮拨打电话为例:
第一种:在Activity中自定义了一个OnClickListener的实现类;
第二种:在button.setOnClickListener()方法中写一个内部类;
第三种:让Activity实现OnClickListener接口,实现onClick方法;
第四种:在布局文件中,给按钮设置onClick属性,然后在Activity中写方法(public void call(View v));
(4种方法各有优劣,在实际使用过程中根据具体情况进行选择使用)
1、内部类的方法:
(1)在布局文件中定义按钮的ID:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="拨打"
android:id="@+id/bt"
/>
(2)在代码中给按钮添加监听事件:
private EditText et_phone;
private Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
et_phone = (EditText) findViewById(R.id.et_phone);
bt = (Button) findViewById(R.id.bt);
bt.setOnClickListener(new OnClickListener() {
//点击按钮之后才会调用这个方法
@Override
public void onClick(View v) {
String phone = et_phone.getText().toString().trim();
if(TextUtils.isEmpty(phone)){
Toast.makeText(MainActivity.this, "电话号码不能为空", Toast.LENGTH_SHORT).show();
}else{
//拨打电话号码
Intent intent = new Intent();
//设置 拨打电话的动作
intent.setAction(Intent.ACTION_CALL);
//设置数据
intent.setData(Uri.parse("tel://"+phone));
//调用拨打电话号码的功能
startActivity(intent);
}
}
});
}
2、自定义一个监听器类:
private class MyListener implements OnClickListener{
@Override
public void onClick(View v) {
//点击按钮之后才会调用这个方法
String phone = et_phone.getText().toString().trim();
if(TextUtils.isEmpty(phone)){
Toast.makeText(MainActivity.this, "电话号码不能为空", Toast.LENGTH_SHORT).show();
}else{
//拨打电话号码
Intent intent = new Intent();
//设置 拨打电话的动作
intent.setAction(Intent.ACTION_CALL);
//设置数据
intent.setData(Uri.parse("tel://"+phone));
//调用拨打电话号码的功能
startActivity(intent);
}
}
}
3、在布局文件中给按钮添加一个单击事件的响应方法,然后再中添加一个方法:
布局文件:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="拨打"
//定义方法
android:onClick="call"
/>
代码:
public void call(View view){
String phone = et_phone.getText().toString().trim();
if(TextUtils.isEmpty(phone)){
Toast.makeText(this, "电话号码不能为空", Toast.LENGTH_SHORT).show();
}else{
//拨打电话号码
Intent intent = new Intent();
//设置 拨打电话的动作
intent.setAction(Intent.ACTION_CALL);
//设置数据
intent.setData(Uri.parse("tel://"+phone));
//调用拨打电话号码的功能
startActivity(intent);
}
}
4、是activity实现OnClickListener接口,重新onClick方法:
public class MainActivity extends Activity implements OnClickListener{
private EditText et_phone;
private Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
et_phone = (EditText) findViewById(R.id.et_phone);
bt = (Button) findViewById(R.id.bt);
//添加单击事件的监听器
bt.setOnClickListener(this);
}
//实现接口的方法
public void onClick(View v) {
String phone = et_phone.getText().toString().trim();
if(TextUtils.isEmpty(phone)){
Toast.makeText(MainActivity.this, "电话号码不能为空", Toast.LENGTH_SHORT).show();
}else{
//拨打电话号码
Intent intent = new Intent();
//设置 拨打电话的动作
intent.setAction(Intent.ACTION_CALL);
//设置数据
intent.setData(Uri.parse("tel://"+phone));
//调用拨打电话号码的功能
startActivity(intent);
}
}