Home » Android » java – SpannableString#setSpan set wrong text range-Exceptionshub

java – SpannableString#setSpan set wrong text range-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I use following code, it wrap wrong text range to bold

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

the result is like following:

enter image description here

I’m confused ss.charAt(12) return ‘2’, but setSpan, when i setSpan with end “12”, span doesn’t include “2”

How to&Answers:

I find setSpan(span, start, end, flag), “start” is first char index, and “end” is “last char index + 1”, I don’t know it’s bug or expected

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

I guess setSpan use 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) {