【问题标题】:highlight the queried text in the recycleView list ignoring space在 recycleView 列表中突出显示查询的文本,忽略空格
【发布时间】:2019-11-05 20:22:34
【问题描述】:

我试图在 recycleView 列表中突出显示查询的文本。 我的要求是忽略空格并突出显示文本。

我的名单:[“罗伯特·德尼罗”、“杰克·尼科尔森”、“马龙·白兰度”]

搜索查询:德尼罗

预期:罗伯特 De Niro

下面是我的代码

  private Spannable getHighlightedText(String wholeText, String searchText) {

    if (searchText != null && wholeText.toLowerCase().contains(searchText.toLowerCase())) {
        int startPos = wholeText.toLowerCase().indexOf(searchText.toLowerCase());
        int endPos = startPos + searchText.length();

        Spannable spanString = Spannable.Factory.getInstance().newSpannable(wholeText);
        spanString.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.primary)), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spanString;
    }

    return new SpannableString(wholeText);
}

【问题讨论】:

    标签: android searchview spannablestring


    【解决方案1】:

    在检查之前从搜索字符串中删除空格

    searchText= searchText.trim().replace(" ", "");
    

    你的功能会是这样的

    private Spannable getHighlightedText(String wholeText, String searchText) {
    
    
      String searchTextWithOutSpace=searchText.trim().replace(" ", "");
    
    
      if (searchText != null && ( wholeText.toLowerCase().contains(searchTextWithOutSpace.toLowerCase()) ||
          //add another condition because mybae user write searchText with space  
          wholeText.toLowerCase().contains(searchText.toLowerCase())) ) {
        int startPos = wholeText.toLowerCase().indexOf(searchText.toLowerCase());
        int endPos = startPos + searchText.length();
    
        Spannable spanString = Spannable.Factory.getInstance().newSpannable(wholeText);
        spanString.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.primary)), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spanString;
      }
    
      return new SpannableString(wholeText);
    }
    

    【讨论】:

    • 如果我这样做了,那么 searchText= searchText.trim().replace(" ", ""); 然后 . int startPos = wholeText.toLowerCase().indexOf(searchText.toLowerCase()); 将返回 -1
    • 感谢您的帮助。我将用一个例子来解释它。 wholeText = "Mahmoud Abu Elheja" searchText = "AbuE" 所以按照你的逻辑,我们正在制作小写并删除空格 searchTextWithOutSpace = "abue"下面的行将返回 -1 wholeText.toLowerCase().indexOf(searchText.toLowerCase()); "mahmoud bbu elheja".indexOf("abue")
    • @Ananth No 我在使用 indexOf 时使用 (searchText) 而不是 (searchTextWithOutSpace) 所以:"mahmoud abu elheja".indexOf("abu e")
    猜你喜欢
    • 2019-10-27
    • 2011-02-12
    • 2020-07-08
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    相关资源
    最近更新 更多