<span style="font-family:Comic Sans MS;font-size:18px;">package com.huawei.dialphone;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener{
private Button dialButton;
private EditText phoneNum;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialButton = (Button)findViewById(R.id.dial);
phoneNum = (EditText)findViewById(R.id.phone);
<span style="color:#ff0000;">//第一种:使用内部类来实现按钮监听</span>
DialListener listener = new DialListener();
dialButton.setOnClickListener(listener);
<span style="color:#ff0000;">//第二种:创建匿名类的实例,并赋给成员变量</span>
dialButton.setOnClickListener(this.listener);
<span style="color:#ff0000;"> //第三种:直接使用匿名内部类的匿名实例来实现按钮的监听</span>
dialButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String phoneNumText = phoneNum.getText().toString();
if(( phoneNumText != null) && (!"".equals(phoneNumText.trim()))){
// Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phoneNumText));
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + phoneNumText));
startActivity(intent);
}
}
});
<span style="color:#ff0000;">//第四种:自身实现监听接口,完成按钮点击事件的响应</span>
dialButton.setOnClickListener(this);
}
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String phone = phoneNum.getText().toString();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + phone));
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class DialListener implements View.OnClickListener {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String phone = phoneNum.getText().toString();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + phone));
}
}
/<span style="color:#ff0000;">/第四种:通过类本身实现点击接口来完成按钮的监听</span>
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String phone = phoneNum.getText().toString();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + phone));
}
}
</span>
还有一种写法在代码中无法体现的,就是直接在xml中定义button按钮的时候指定click 要调用的方法即可
android 为按钮添加响应事件的五种写法
最新推荐文章于 2022-08-10 02:05:50 发布