Android 多个按钮发送预定义的短信
大家好,我是编程新手。我试图有多个按钮发送不同的预定义短信到预定义的号码。我不知道如何拥有多个SetOnClickListener New OnClickListener,因为第二个SetOnClickListener New OnClickListener给了我错误。如果没有buttonSend2=Button findViewByIdR.id.buttonSend2,程序工作正常Android 多个按钮发送预定义的短信,android,sms,onclicklistener,Android,Sms,Onclicklistener,大家好,我是编程新手。我试图有多个按钮发送不同的预定义短信到预定义的号码。我不知道如何拥有多个SetOnClickListener New OnClickListener,因为第二个SetOnClickListener New OnClickListener给了我错误。如果没有buttonSend2=Button findViewByIdR.id.buttonSend2,程序工作正常 public class SendSMSActivity extends Activity { But
public class SendSMSActivity extends Activity {
Button buttonSend;
Button buttonSend2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend2 = (Button) findViewById(R.id.buttonSend2);
buttonSend.setOnClickListener(new OnClickListener() {
buttonSend2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonSend:
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "abc");
sendIntent.putExtra("address", "9909990");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
break;
case R.id.buttonSend2:
Intent sendIntent1 = new Intent(Intent.ACTION_VIEW);
sendIntent1.putExtra("sms_body", "def");
sendIntent1.putExtra("address", "012345678");
sendIntent1.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent1);
break;
}
}
});
});
}
}
谢谢大家! 看起来你的点击听众有点困惑。试试这个:
buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend2 = (Button) findViewById(R.id.buttonSend2);
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonSend:
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "abc");
sendIntent.putExtra("address", "9909990");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
break;
case R.id.buttonSend2:
Intent sendIntent1 = new Intent(Intent.ACTION_VIEW);
sendIntent1.putExtra("sms_body", "def");
sendIntent1.putExtra("address", "012345678");
sendIntent1.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent1);
break;
}
}
};
buttonSend.setOnClickListener(listener);
buttonSend2.setOnClickListener(listener);
本·皮尔森的回答是完全正确的,但我想我会留下一个选择,以防你做的事情更容易 您可以让activity类实现View.onClickListener,然后只需在类中使用一个onClickView v方法和一个switch语句,如上所述
这是一个非常微妙的区别,但是如果您在不同的方法中隐藏或显示不同的可单击对象,并且不希望onClickListener使用类变量,那么此实现可能对您很有用。谢谢您的回复。程序在我身上有2个错误,1个在按钮SEND2处;另一个1位于buttonSend2.setOnClickListenerlistener;两个错误都是相同的:yntax错误,插入}以完成类体。尝试在不同的位置插入},但仍然不起作用。对不起,我是个新手,努力学习谢谢!现在问题解决了。代码运行良好。刚才的问题是我忘了再添加2个{最后…太专注于你的代码了谢谢你的替代方法