我试图从所选文本中删除粗体文本,但是当我点击按钮时,它取消了我之前加粗的所有文本。似乎 removeSpan.styleSpan[i] 没有处理我选择的文本的哪一部分,而是从整个粗体范围字符串中删除了粗体文本。
这是我在一个按钮下使用的代码
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);
}
最佳答案
您正在使用此文本:
Spannable str = texto.getText();
并且您正在搜索选定范围内的跨度:
styleSpans = str.getSpans(selectionStartb, selectionEndb, StyleSpan.class);
了解这里发生的事情很重要。您没有在选择范围内获得所有“跨区文本”,甚至所有 StyleSpan
;您将获得应用于整个 文本的所有 StyleSpan
,只要它们至少有一部分应用于所选范围。
换句话说,即使您只选择了跨文本的一部分,StyleSpan
对象仍然代表整个跨文本。
您将不得不修改您的代码以处理所有不同的可能情况:
- 所选范围没有跨度 -> 为所选范围添加跨度
- 所选范围与单个范围完全匹配 -> 删除该范围
- 所选范围已完全跨越,但未覆盖整个范围 -> 删除现有范围并重新添加一个范围到先前跨越但未选中的范围
- 所选范围只是部分跨越,覆盖了整个范围 -> 删除现有范围并为所选范围添加一个范围
- 所选范围仅部分跨越,但未覆盖整个范围 -> 删除现有跨度并为所选范围添加一个跨度 + 先前跨越但未选中的范围
关于java - removeSpan(styleSpans[i]) 从带样式的文本中移除之前的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53235308/