我正在尝试使用以下代码来捕获用户何时输入@symbol然后进行高亮 tag_color中的前置文本,无论它在 mPostTextView 中的哪个位置键入。我对安卓开发还比较陌生,所以我不确定 为什么我收到以下错误消息,指的是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)
试试这个,还要检查字符序列长度,
if (charSequence!=null && String.valueOf(charSequence.charAt(count-1)).equal("@")) {
....}