【问题标题】:Replacing upper-case with upper-case and lower-case with lower-case大写替换大写,小写替换小写
【发布时间】:2019-04-07 23:04:35
【问题描述】:

搜索后我在 textviews 中突出显示文本并替换为这段代码..

 txtV.setText(Html.fromHtml((text.replaceAll("(?i)" 
    + searchText,"<font color='#53f721'>" + searchText + "</font>")));

但是所有的大写字符都被小写替换了。 我希望将大写字符替换为大写,小写字符替换为小写。

提前致谢。

【问题讨论】:

  • 请在您的问题中添加明确的问题陈述。另外,我怀疑您对当前行为的描述。也许还可以添加一些示例数据。

标签: android android-layout


【解决方案1】:

实际上,您正在用searchText 替换原始文本,并且使用(?i) 替换功能不区分大小写。

如果我想这样做,我更喜欢使用SpannableString,如下所示:

String originalText = "Your original text";
Spannable wordToSpan = new SpannableString(originalText);
originalText = originalText.toLowerCase();
searchText = searchText.toLowerCase();
int length = searchText.length();
int index = originalText.indexOf(searchText);
while (index >= 0) {
    wordToSpan.setSpan(new ForegroundColorSpan(Color.BLUE), index, index + length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    index = originalText.toLowerCase().indexOf(searchText, index + length);
}
txtV.setText(wordToSpan);

【讨论】:

  • 谢谢@Mir Milad Hosseiny
【解决方案2】:

您可以通过以下方式使用正则表达式功能:

txtV.setText(Html.fromHtml((text.replaceAll("(?i)" 
    + searchText,"<font color='#53f721'>$0</font>")));

【讨论】:

    猜你喜欢
    • 2013-10-15
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    • 2015-04-24
    • 1970-01-01
    相关资源
    最近更新 更多