SpannableString#setSpan设置错误的文本范围

问题描述 投票:1回答:1

我使用以下代码,将错误的文本范围换成粗体

    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);

结果如下:

enter image description here

我很困惑ss.charAt(12)返回'2',但是setSpan,当我将setSpanend“ 12”一起使用时,span不包含“ 2”]

java android
1个回答
0
投票

我发现setSpan(span,start,end,flag),“ start”是第一个字符索引,“ end”是“最后一个字符索引+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) {
© www.soinside.com 2019 - 2024. All rights reserved.