我试图从选中的文本中删除粗体文本,但当我点击按钮时,它会取消所有我之前加粗的文本。看起来removeSpan.styleSpani并没有注意到我选择了文本的哪一部分,而是从整个粗体的跨度字符串中删除了粗体文本。
我希望选定的部分不加粗,仅如图所示

但是在点击remove span按钮后,它会像这样取消整行的粗体显示

下面是我在一个按钮上使用的代码
private void boldText(){
int selectionStartb = texto.getSelectionStart();
int selectionEndb = texto.getSelectionEnd();
if (selectionStartb > selectionEndb) {
int temp = selectionEndb;
selectionEndb = selectionStartb;
selectionStartb = temp;
}
if (selectionEndb > selectionStartb) {
Spannable str = texto.getText();
boolean BL = false;
StyleSpan[] styleSpans;
styleSpans = str.getSpans(selectionStartb, selectionEndb, StyleSpan.class);
// If the selected text-part already has BOLD style on it, then
// we need to disable it
for (int i = 0; i < styleSpans.length; i++) {
if (styleSpans[i].getStyle() == android.graphics.Typeface.BOLD) {
str.removeSpan(styleSpans[i]);
BL = true;
}
}
// Else we set BOLD style on it
if (!BL) {
str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), selectionStartb, selectionEndb,
Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
texto.setSelection(selectionStartb, selectionEndb);
}}
发布于 2018-11-10 11:39:26
您正在使用此文本:
可扩展字符串= texto.getText();
并且您正在搜索选定范围内的跨度:
styleSpans = str.getSpans(selectionStartb,selectionEndb,StyleSpan.class);
理解这里发生的事情是很重要的。您不会获得所选内容中的所有“跨区文本”,甚至不是所有StyleSpan;您将获得应用于整个文本的所有StyleSpan,只要它们中至少有一部分应用于所选范围。
换句话说,即使只选择了部分跨区文本,StyleSpan对象仍然表示整个跨区文本。
您必须修改您的代码以处理所有不同的可能情况:
<->>H118仅部分跨区并覆盖以前已跨区但未选定的范围
发布于 2021-01-23 14:53:29
如果问题仍然是实际的
而不是这一行:
str.removeSpan(styleSpans[i]);尝试使用类似下面这几行的代码:
StyleSpan styleSpan = styleSpans[i]
// Get start and end of current span (not current selection)
int spanStart = str.getSpanStart(styleSpan);
int spanEnd = str.getSpanEnd(styleSpan);
// Remove span which contains current selection (This is your code line)...
str.removeSpan(styleSpan);
// Check if current selection is not the same as current span object
if (selStart!= spanStart || selEnd != spanEnd){
// Create new span object before! current selection
if (selStart - 1 > spanStart && selStart - 1 >= 0){
str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),
spanStart,
selStart - 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
// Create new span object after! current selection
if (spanEnd > selEnd + 1 && selEnd + 1 < str.length()){
str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),
selEnd + 1,
spanEnd, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
}https://stackoverflow.com/questions/53235308
复制相似问题