gpt4 book ai didi

android - EditText 上的 setSpan() 删除其他跨度

转载 作者:搜寻专家 更新时间:2023-11-01 07:51:34 26 4
gpt4 key购买 nike

我有一个 bold 按钮,当按下该按钮时,应该会更改 EditText 字段 中所选文本的字体。这一切都完美无缺,只有一个异常(exception)。如果 EditText 中的其他地方有 bold 字体,我尝试创建一个新的 bold 部分,原来的部分被改回 正常。例如,这个字符串:

粗体 不粗体更粗体。

如果我突出显示任何普通单词并按下按钮,它们会变成粗体,但第一个单词会变成普通。我在我的代码中看不到任何原因。

谢谢!

final StyleSpan normalStyle = new StyleSpan(Typeface.NORMAL);
final StyleSpan boldStyle = new StyleSpan(Typeface.BOLD);
boldButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int startSelection = field.getSelectionStart();
int endSelection = field.getSelectionEnd();
Editable editableText = field.getText();

StyleSpan[] selectedSpans = editableText.getSpans(startSelection, endSelection, StyleSpan.class);
boolean isAlreadyBold = false;
for (StyleSpan style : selectedSpans) {
print("The style is " + style.getStyle());
if (style.getStyle() == Typeface.BOLD) {
int styleStart = editableText.getSpanStart(style);
int styleEnd = editableText.getSpanEnd(style);
if (styleStart == startSelection && styleEnd == endSelection) {
editableText.removeSpan(style);
editableText.setSpan(normalStyle, startSelection, endSelection, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
isAlreadyBold = true;
print("Spans are equal");
} else if (styleStart < startSelection && styleEnd > endSelection) {
editableText.removeSpan(style);
editableText.setSpan(boldStyle, styleStart, startSelection, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editableText.setSpan(boldStyle, endSelection, styleEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editableText.setSpan(normalStyle, startSelection, endSelection, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
isAlreadyBold = true;
print("Style is larger than selection");
} else if (styleStart < startSelection && styleEnd >= startSelection) {
editableText.removeSpan(style);
editableText.setSpan(boldStyle, styleStart, startSelection, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editableText.setSpan(normalStyle, startSelection, endSelection, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
isAlreadyBold = true;
print("Style begins before selection");
} else if (endSelection < styleEnd && endSelection >= styleStart) {
editableText.removeSpan(style);
editableText.setSpan(boldStyle, endSelection, styleEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editableText.setSpan(normalStyle, startSelection, endSelection, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
isAlreadyBold = true;
print("Style ends after selection");
}
}
}
if (!isAlreadyBold) {
editableText.setSpan(boldStyle, startSelection, endSelection, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
}
});

注意:- print 是我添加的实用程序日志

最佳答案

I can't see any reason for this in my code.

为每个跨接区域创建一个新的 StyleSpan。不要重复使用已在使用中的 StyleSpan 实例。

关于android - EditText 上的 setSpan() 删除其他跨度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34375401/

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