Android高亮文字

时间:2017-03-27 15:41:10

标签: android-edittext android-webview textview background-color highlight android

我正在写一本书。在这个应用程序中,用户必须熟练地阅读和突出显示文本。我在互联网上搜索了很多,并使用了webview,textview,纯文本但没有成功。我怎样才能做到这一点?能够通过各种方式突出显示文本。

3 个答案:

答案 0 :(得分:0)

试试这个图书馆Android TextHighlighter

实现

TextView.setText()获取的参数Spannable不仅仅是CharacterSequence。 SpannableString有一个允许应用样式的方法setSpan()

参见CharacterStyle https://developer.android.com/reference/android/text/style/CharacterStyle.html

的直接子类列表
  • 在“Hello,World”
  • 中为单词“Hello”提供背景颜色和前景色的示例
Spannable spannable = new SpannableString("Hello, World");
// setting red foreground color
ForegroundSpan fgSpan = new ForegroundColorSpan(Color.red);
// setting blue background color
BackgroundSpan bgSpan = new BackgroundColorSPan(Color.blue);

// setSpan requires start and end index
// in our case, it's 0 and 5
// You can directly set fgSpan or bgSpan, however,
// to reuse defined CharacterStyle, use CharacterStyle.wrap()
spannable.setSpan(CharacterStyle.wrap(fgSpan), 0, 5, 0);
spannable.setSpan(CharacterStyle.wrap(bgSpan), 0, 5, 0);

// apply spannableString on textview
textView.setText(spannable);

link

有更多答案

答案 1 :(得分:0)

这对你有用,

SpannableString str = new SpannableString("Highlighted. Not highlighted.");
 str.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 11, 0); 
 textView.setText(str);

答案 2 :(得分:0)

/** This is the way you can use Matcher, i think you are going to type in editext and textview's text should be highlioghted so this is the way...    

 search_icon.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Searched_text.setVisibility(View.VISIBLE);

                   String tvt = textView_searching.getText().toString();
                    String ett = Searched_text.getText().toString();
                    SpannableStringBuilder sb = new SpannableStringBuilder(tvt);
                    Pattern p = Pattern.compile(ett, Pattern.CASE_INSENSITIVE);
                    Matcher m = p.matcher(tvt);
                    while (m.find()){
                        //String word = m.group();
                        //String word1 = notes.substring(m.start(), m.end());

                        sb.setSpan(new ForegroundColorSpan(Color.RED), m.start(), m.end(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                        sb.setSpan(new BackgroundColorSpan(Color.YELLOW), m.start(), m.end(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                    }
                    textView_searching.setText(sb);

                }
            });