我如何编写每个按钮的完整代码,就像我为button1所做的那样? 我想要从多个按钮调用相同的方法,如button1。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button one = (Button) findViewById(R.id.button1);
one.setOnClickListener(this); // calling onClick() method
}
@Override
public void onClick(View v) {
String phoneNumber = ((EditText) findViewById(R.id.editView4)).getText().toString();
try {
{
SmsManager.getDefault().sendTextMessage(phoneNumber, null, "A", null, null);
}
} catch (Exception e) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
AlertDialog dialog = alertDialogBuilder.create();
dialog.setMessage(e.getMessage());
dialog.show();
}
}
public void Openinformation(View view) {
setContentView(R.layout.information);
}
}
答案 0 :(得分:1)
您可以让按钮全部使用相同的OnClickListener
,然后检查点击了哪个视图以确定要发送的消息
@Override
public void onClick(View v) {
String phoneNumber = ((EditText) findViewById(R.id.editView4)).getText().toString();
try {
String message;
if (v.getId() == R.id.button1) {
message = "A";
}
else if (v.getId() == R.id.button2) {
message = "B";
}
SmsManager.getDefault().sendTextMessage(phoneNumber, null, message, null, null);
} catch (Exception e) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
AlertDialog dialog = alertDialogBuilder.create();
dialog.setMessage(e.getMessage());
dialog.show();
}
}
答案 1 :(得分:0)
您可以像对待其他按钮一样:
Button one = (Button) findViewById(R.id.button1);
one.setOnClickListener(this); // calling onClick() method
Button two = (Button) findViewById(R.id.button2);
two.setOnClickListener(this); // calling the same onClick()