java - removeSpan(styleSpans[i]) 从带样式的文本中移除之前的样式

标签 java android

我试图从所选文本中删除粗体文本,但是当我点击按钮时,它取消了我之前加粗的所有文本。似乎 removeSpan.styleSpan[i] 没有处理我选择的文本的哪一部分,而是从整个粗体范围字符串中删除了粗体文本。

我希望所选部分仅如图所示不加粗 enter image description here

但是在点击删除跨度按钮后,它会像这样取消整行 enter image description here

这是我在一个按钮下使用的代码

 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/

相关文章:

java - 如何使用用户类型在 JPA 中使用 Hibernate 持久化 JSR 310 java.time.LocalDateTime

android - 如何解决拆分的 apk 和 bundle 的版本代码之间的冲突?

java - 我想在满足条件时更改 PaintComponent() 对象的颜色

java - 如何锁定作为枚举的泛型类型

java - 叠加几个 JProgressBars?

java - 运行小程序时摆脱 Java 部署工具包

java - Android Realm 中的一对多关系。处理线程

android - 将 token 添加到 Vimeo API Android 的 header

java - Android:如何使异步任务 hibernate ,同时评估某些条件

android - 如何在 Windows XP 上的单个批处理文件中执行 "android update project"命令列表?