我使用以下代码,它将错误的文本范围包装为粗体
final StyleSpan span = new StyleSpan(BOLD);
SpannableString ss = new SpannableString("line 1\nline 2");
Log.d(getPackageName(), String.valueOf(ss.charAt(12)));
ss.setSpan(span, 7, 12, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
((TextView) findViewById(R.id.text)).setText(ss);
结果如下:
我很困惑
ss.charAt(12)
返回'2',但是setSpan,当我setSpan
与end
为“ 12”时,范围不包括“ 2” 最佳答案
我发现setSpan(span,start,end,flag),“开始”是第一个字符索引,“结束”是“最后一个字符索引+ 1”,我不知道它是错误还是预期的
final ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
SpannableString ss = new SpannableString("line 1\nline 2");
Log.d(getPackageName(), String.valueOf(ss.charAt(12)));
ss.setSpan(span, 0, 13, 0);
((TextView) findViewById(R.id.text)).setText(ss);
我猜setSpan使用String#substring:
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified substring.
* @exception IndexOutOfBoundsException if the
* {@code beginIndex} is negative, or
* {@code endIndex} is larger than the length of
* this {@code String} object, or
* {@code beginIndex} is larger than
* {@code endIndex}.
*/
public String substring(int beginIndex, int endIndex) {