使用外部类作为事件监听器
实现了OnLongClickListener接口
代码如下:
public class SendSmsListener implements OnLongClickListener {
private Activity act;
private EditText address;
private EditText content;
//创建构造器:
public SendSmsListener(Activity act,EditText address,EditText content){
this.act=act;
this.address=address;
this.content=content;
}
@Override
public boolean onLongClick(View arg0) {
// TODO Auto-generated method stub
//将文本转换为字符串
String st1=address.getText().toString();
String st2=content.getText().toString();
//获取短信管理器
SmsManager smsManager=SmsManager.getDefault();
//创建发送短信的pendingIntent
PendingIntent sentIntent=PendingIntent.getBroadcast(act, 0, new Intent(), 0);
//发送文本短信
smsManager.sendTextMessage(st1, null,st2, sentIntent,null);
Toast.makeText(act,"发送完毕", Toast.LENGTH_LONG).show();
return false;
}
}
布局代码很简单此处略去:
java代码如下
public class MainActivity extends Activity {
EditText address;
EditText content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
address=(EditText) findViewById(R.id.address);
content=(EditText) findViewById(R.id.content);
Button bn=(Button) findViewById(R.id.send);
//为按钮设置长按监听器并实现SendSmsListener的构造方法;
bn.setOnLongClickListener(new SendSmsListener(
this , address, content));
}