我正在尝试使用以下代码来捕获用户输入@symbol然后出现高光的情况 无论在mPostTextView中的何处键入,tag_color中的后续文本。我还是Android开发的新手,所以我不确定 为什么我得到以下错误消息,引用java.lang.IndexOutOfBoundsException:charAt:....如下所示 这似乎与charAt(start)语句的长度有关。谁能阐明这一点?
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
//@Mentions for tagging user
if (charSequence.charAt(start) == '@') {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(mPostToText.getText().toString());
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.tag_color));
spannableStringBuilder.setSpan(foregroundSpan, start, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mPostToText.setText(spannableStringBuilder);
}
这是来自日志
java.lang.IndexOutOfBoundsException: charAt: 22 >= length 22
at android.text.SpannableStringBuilder.charAt(SpannableStringBuilder.java:119)
at com.tradezapp.tradezapp.gui.activity.CreatePostActivity$CreatePostFragment$2$override.onTextChanged(CreatePostActivity.java:193)
at com.tradezapp.tradezapp.gui.activity.CreatePostActivity$CreatePostFragment$2$override.access$dispatch(CreatePostActivity.java)
at com.tradezapp.tradezapp.gui.activity.CreatePostActivity$CreatePostFragment$2.onTextChanged(CreatePostActivity.java)
答案 0 :(得分:0)
尝试一下,还要检查charSequence的长度,
if (charSequence!=null && String.valueOf(charSequence.charAt(count-1)).equal("@")) {
....}