public void onClick(View view) { switch (view.getId()) { case R.id.send: String content = mChatEdittext.getText().toString(); if (content != null && !content.isEmpty()) { Chat chat = new Chat(Chat.SEND, content); mChatlist.add(chat); mAdapter.notifyDataSetChanged(); hideSoftKey(); mHandler.sendEmptyMessageDelayed(AUTORECEIVE, 1000); } else { Toast.makeText(this, "不能发送空的信息", Toast.LENGTH_SHORT).show(); } break; default: break; } } 这段代码为什么会报constant expression required
时间: 2024-01-11 11:05:30 浏览: 34
这段代码报错的原因是因为在switch语句中,case后面的值必须是一个常量表达式,而view.getId()方法返回的值不是常量表达式,因此无法在case后面使用。
要解决这个问题,可以使用if-else语句替代switch语句。例如:
```
public void onClick(View view) {
if (view.getId() == R.id.send) {
String content = mChatEdittext.getText().toString();
if (content != null && !content.isEmpty()) {
Chat chat = new Chat(Chat.SEND, content);
mChatlist.add(chat);
mAdapter.notifyDataSetChanged();
hideSoftKey();
mHandler.sendEmptyMessageDelayed(AUTORECEIVE, 1000);
} else {
Toast.makeText(this, "不能发送空的信息", Toast.LENGTH_SHORT).show();
}
}
}
```
这样就可以避免使用switch语句时出现的“constant expression required”错误。