• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.contacts.format;
18 
19 import android.text.SpannableString;
20 import android.text.style.ForegroundColorSpan;
21 import android.widget.TextView;
22 
23 /**
24  * Highlights the text in a text field.
25  */
26 public class PrefixHighlighter {
27     private final int mPrefixHighlightColor;
28 
29     private ForegroundColorSpan mPrefixColorSpan;
30 
PrefixHighlighter(int prefixHighlightColor)31     public PrefixHighlighter(int prefixHighlightColor) {
32         mPrefixHighlightColor = prefixHighlightColor;
33     }
34 
35     /**
36      * Sets the text on the given text view, highlighting the word that matches the given prefix.
37      *
38      * @param view the view on which to set the text
39      * @param text the string to use as the text
40      * @param prefix the prefix to look for
41      */
setText(TextView view, String text, char[] prefix)42     public void setText(TextView view, String text, char[] prefix) {
43         view.setText(apply(text, prefix));
44     }
45 
46     /**
47      * Returns a CharSequence which highlights the given prefix if found in the given text.
48      *
49      * @param text the text to which to apply the highlight
50      * @param prefix the prefix to look for
51      */
apply(CharSequence text, char[] prefix)52     public CharSequence apply(CharSequence text, char[] prefix) {
53         int index = FormatUtils.indexOfWordPrefix(text, prefix);
54         if (index != -1) {
55             if (mPrefixColorSpan == null) {
56                 mPrefixColorSpan = new ForegroundColorSpan(mPrefixHighlightColor);
57             }
58 
59             SpannableString result = new SpannableString(text);
60             result.setSpan(mPrefixColorSpan, index, index + prefix.length, 0 /* flags */);
61             return result;
62         } else {
63             return text;
64         }
65     }
66 }
67