gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:05:11 27 4
gpt4 key购买 nike

我使用以下代码,它将错误的文本范围包装为粗体

    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”

最佳答案

我发现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) {

关于java - SpannableString#setSpan 设置错误的文本范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60292632/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com