Android - 短信应用程序中的 onClick 错误
我有一个发送消息的按钮 - 但是,当我告诉 onClickListener 中的 onClick 功能在单击时禁用该按钮以及当我为其设置 toast 时,它似乎给了我一些错误。哦,错误在“else”下划线表示语法错误。 (除此之外,代码工作正常并发送短信)
public void onClick(View v)
{
messageinfo mi = new messageinfo();
String message = txtMessage.getText().toString();
if (message.length()>0)
sendSMS(mi.SMSNO(), smsmessage);
Toast.makeText(getBaseContext(), "sending", Toast.LENGTH_SHORT).show();
myButton.setEnabled(false);
else
Toast.makeText(getBaseContext(), "enter your message", Toast.LENGTH_SHORT).show();
}
有一个简单的解决方案吗?
I have a button that sends message - however the onClick feature in the onClickListener seems to give me a few errors when I tell it to disable the button when click, AND when I set toast to it. Oh, and the error underlines 'else' saying syntax error. (Other than that the code works fine and sends the SMS)
public void onClick(View v)
{
messageinfo mi = new messageinfo();
String message = txtMessage.getText().toString();
if (message.length()>0)
sendSMS(mi.SMSNO(), smsmessage);
Toast.makeText(getBaseContext(), "sending", Toast.LENGTH_SHORT).show();
myButton.setEnabled(false);
else
Toast.makeText(getBaseContext(), "enter your message", Toast.LENGTH_SHORT).show();
}
Is there an easy solution to this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通过格式化您的代码,我注意到您的 if 语句似乎失败了。
您需要在 if 语句的结果代码周围添加
{ }
,例如:您唯一可能错过
{ }
的时候是当您只得到if 之后的一个语句。然而,这始终是一个坏主意,仅仅投入一些{ }
并不需要付出太多努力,并且意味着这样的问题永远不会发生。澄清
您问题中的代码正在运行
if
,如果匹配,则运行下一行。然后代码在 if 子句之外执行(因为缺少括号),因此无论if
语句的结果如何,都将运行接下来的两行。然后它遇到了它不期望的
else
。它应该位于{ .. }
之后,或者直接位于 if 之后的第一个语句之后,所以这就是它在else
处失败的原因。Through formatting your code I've noticed that it would appear that your if statement is failing.
You need to have
{ }
s around the resulting code from an if statement, eg:The only time you can miss out the
{ }
s is when you've only got ONE statement following an if. This is always a bad idea however, its not much effort just to put in some{ }
s, and means that issues like this won't ever happen.Clarification
The code in your question is running the
if
and if it matches it runs THE NEXT LINE. Then the code carries on OUTSIDE of the if clause (because of missing brackets)so then will run the next two lines REGARDLESS of the outcome of theif
statement.Then it encounters the
else
which its not expecting. Its supposed to be after either{ .. }
or directly after the FIRST statement after the if, so that's why it fails at theelse
.