如何创建像Adobe Reader或Medium这样的高亮文本视图?

时间:2019-03-25 19:19:22

标签: java android string kotlin textview

伙计们。 我在这里需要一些启发。我想创建一个具有突出显示功能的应用程序,就像下面的屏幕截图一样。但是,我不知道如何执行此操作。我认为Spannable TextView只能帮不了我。你有什么主意吗 谢谢。

Example of highlight menu in Medium App

1 个答案:

答案 0 :(得分:0)

您可以使用SpannableString

要突出显示特定文本,请使用此方法。

private void highlightString(String input) {
//Get the text from text view and create a spannable string
SpannableString spannableString = new SpannableString(mTextView.getText());
//Get the previous spans and remove them
BackgroundColorSpan[] backgroundSpans = spannableString.getSpans(0, spannableString.length(), BackgroundColorSpan.class);

for (BackgroundColorSpan span: backgroundSpans) {
    spannableString.removeSpan(span);
}

//Search for all occurrences of the keyword in the string
int indexOfKeyword = spannableString.toString().indexOf(input);

while (indexOfKeyword > 0) {
    //Create a background color span on the keyword
    spannableString.setSpan(new BackgroundColorSpan(Color.YELLOW), indexOfKeyword, indexOfKeyword + input.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    //Get the next index of the keyword
    indexOfKeyword = spannableString.toString().indexOf(input, indexOfKeyword + input.length());
}

//Set the final text on TextView
mTextView.setText(spannableString);}