|
3 | 3 | import android.support.annotation.NonNull;
|
4 | 4 | import android.support.annotation.Nullable;
|
5 | 5 | import android.text.Html;
|
| 6 | +import android.text.SpannableString; |
6 | 7 | import android.text.Spanned;
|
| 8 | +import android.text.TextUtils; |
7 | 9 |
|
8 | 10 | import java.util.Collection;
|
9 | 11 | import java.util.regex.Matcher;
|
@@ -71,4 +73,39 @@ public static Spanned getHtml(@NonNull final String text) {
|
71 | 73 | return Html.fromHtml(text);
|
72 | 74 | }
|
73 | 75 | }
|
| 76 | + |
| 77 | + /** |
| 78 | + * Examples : |
| 79 | + * - <code>span(new UnderlineSpan(), "all of this is underlined")</code> |
| 80 | + * - <code>span(new StyleSpan(Typeface.BOLD), "all of this is bold")</code> |
| 81 | + * |
| 82 | + * @param spanToApply Object spanToApply |
| 83 | + * @param all CharSequence all |
| 84 | + * @return SpannableString |
| 85 | + */ |
| 86 | + @NonNull |
| 87 | + public static SpannableString span(@NonNull final Object spanToApply, @NonNull final CharSequence all) { |
| 88 | + return span(spanToApply, all, null); |
| 89 | + } |
| 90 | + |
| 91 | + /** |
| 92 | + * Examples : |
| 93 | + * - <code>span(new UnderlineSpan(), "only this is underlined", "this")</code> |
| 94 | + * - <code>span(new StyleSpan(Typeface.BOLD), "only this is bold", "this")</code> |
| 95 | + * |
| 96 | + * @param spanToApply Object spanToApply |
| 97 | + * @param all CharSequence all |
| 98 | + * @param needle CharSequence needle |
| 99 | + * @return SpannableString |
| 100 | + */ |
| 101 | + @NonNull |
| 102 | + public static SpannableString span(@NonNull final Object spanToApply, @NonNull final CharSequence all, @Nullable final CharSequence needle) { |
| 103 | + SpannableString spannableString = new SpannableString(all); |
| 104 | + if (needle != null) { |
| 105 | + spannableString.setSpan(spanToApply, TextUtils.indexOf(all, needle), TextUtils.indexOf(all, needle) + needle.length(), 0); |
| 106 | + } else { |
| 107 | + spannableString.setSpan(spanToApply, 0, all.length(), 0); |
| 108 | + } |
| 109 | + return spannableString; |
| 110 | + } |
74 | 111 | }
|
0 commit comments