我正在使用可扩展字符串来显示textview
中较长段落的更多内容。但是,可能会发生这种情况,即文本视图中只有一行或两个三个单词,不需要阅读更多内容。但是应用程序崩溃并出现错误。
下面是代码:
public class MainViewHolder extends RecyclerView.ViewHolder {
View mView;
public void setDescription(String description) {
TextView post_desc = (TextView) mView.findViewById(R.id.post_desc);
addReadMore(description,post_desc);
}
private void addReadMore(final String text, final TextView textView) {
SpannableString ss = new SpannableString(text.substring(0, 320) + "...\nread more");
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View view) {
addReadLess(text, textView);
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
ds.setTypeface(Typeface.DEFAULT_BOLD);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ds.setColor(getResources().getColor(R.color.purple, getTheme()));
} else {
ds.setColor(getResources().getColor(R.color.purple));
}
}
};
ss.setSpan(clickableSpan, ss.length() - 10, ss.length() , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
private void addReadLess(final String text, final TextView textView) {
SpannableString ss = new SpannableString(text + "\nread less");
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View view) {
addReadMore(text, textView);
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
ds.setTypeface(Typeface.DEFAULT_BOLD);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ds.setColor(getResources().getColor(R.color.purple, getTheme()));
} else {
ds.setColor(getResources().getColor(R.color.purple));
}
}
};
ss.setSpan(clickableSpan, ss.length() - 10, ss.length() , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
}
错误消息:
java.lang.StringIndexOutOfBoundsException: length=11; regionStart=0; regionLength=270
答案 0 :(得分:0)
您必须使用以下内容代替:
SpannableString ss = new SpannableString(text.substring(0, 320) + "...\nread more");
是:
if (text.length() > 320) {
SpannableString ss = new SpannableString(text.substring(0, 320) + "...\nread more");
} else {
SpannableString ss = new SpannableString(text);
}
也在您每次使用时:
ss.setSpan(clickableSpan, ss.length() - 10, ss.length() , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
您确定ss.length() - 10
和ss.length()
是ss
的有效开始和结束部分吗?