1+ /*
2+ * Copyright 2021 Yat Labs
3+ *
4+ * Redistribution and use in source and binary forms, with or
5+ * without modification, are permitted provided that the
6+ * following conditions are met:
7+ *
8+ * 1. Redistributions of source code must retain the above copyright notice,
9+ * this list of conditions and the following disclaimer.
10+ *
11+ * 2. Redistributions in binary form must reproduce the above
12+ * copyright notice, this list of conditions and the following disclaimer in the
13+ * documentation and/or other materials provided with the distribution.
14+ *
15+ * 3. Neither the name of the copyright holder nor the names of
16+ * its contributors may be used to endorse or promote products
17+ * derived from this software without specific prior written permission.
18+ *
19+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
20+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
21+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
24+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
30+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32+ */
33+ package yat.android.ui.extension
34+
35+ import android.text.SpannableString
36+ import android.text.Spanned
37+ import android.text.style.ForegroundColorSpan
38+
39+ internal fun String.applyColorStyle (
40+ defaultColor : Int ,
41+ search : List <String >,
42+ styleColor : Int ,
43+ applyToOnlyFirstOccurence : Boolean = false
44+ ): SpannableString {
45+ val spannableString = SpannableString (this )
46+ spannableString.setSpan(
47+ ForegroundColorSpan (defaultColor),
48+ 0 ,
49+ length,
50+ Spanned .SPAN_INTERMEDIATE
51+ )
52+ search.forEach {
53+ spannableString.applyColorStyle(
54+ it,
55+ styleColor,
56+ applyToOnlyFirstOccurence
57+ )
58+ }
59+ return spannableString
60+ }
61+
62+ private fun SpannableString.applyColorStyle (
63+ search : String ,
64+ color : Int ,
65+ applyToOnlyFirstOccurence : Boolean = false
66+ ) {
67+ var index = this .indexOf(search)
68+ while (index >= 0 ) {
69+ setSpan(
70+ ForegroundColorSpan (color),
71+ index,
72+ index + search.length,
73+ Spanned .SPAN_INTERMEDIATE
74+ )
75+ if (applyToOnlyFirstOccurence) {
76+ break
77+ }
78+ index = this .indexOf(search, index + 1 )
79+ }
80+ }
0 commit comments