使用SpannableString處理字符串工具

public class StringStyleUtils {


? ?public static SpannableString format(Context context, String text, int style) {

? ? ? ?SpannableString spannableString = new SpannableString(text);

? ? ? ?spannableString.setSpan(new TextAppearanceSpan(context, style), 0, text.length(),

? ? ? ? ? ? ? ?0);

? ? ? ?return spannableString;

? ?}

}


圖片發自簡書App

? mTextSwitcher.setFactory(() -> {

? ? ? ? ? ?TextView textView = new TextView(this);

? ? ? ? ? ?textView.setTextAppearance(this, R.style.WebTitle);

? ? ? ? ? ?textView.setSingleLine(true);

? ? ? ? ? ?textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);

? ? ? ? ? ?textView.postDelayed(() -> textView.setSelected(true), 1738);

? ? ? ? ? ?return textView;

? ? ? ?});

? ? ? ?mTextSwitcher.setInAnimation(this, android.R.anim.fade_in);

? ? ? ?mTextSwitcher.setOutAnimation(this, android.R.anim.fade_out);

? ? ? ?if (mTitle != null) setTitle(mTitle);

? ?}設置textview跑馬燈效果,在style中設置具體值。


public class KeywordUtil {

? ?/**

? ? * 關鍵字高亮變色

? ? *

* @param color

* ? ? ? ? ? ?變化的色值

* @param text

* ? ? ? ? ? ?文字

* @param keyword

* ? ? ? ? ? ?文字中的關鍵字

* @return

*/

public static SpannableString matcherSearchTitle(int color, String text,

String keyword) {

SpannableString s = new SpannableString(text);

Pattern p = Pattern.compile(keyword);

Matcher m = p.matcher(s);

while (m.find()) {

int start = m.start();

int end = m.end();

s.setSpan(new ForegroundColorSpan(color), start, end,

Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

}

return s;

}


/**

* 多個關鍵字高亮變色

*

* @param color

* ? ? ? ? ? ?變化的色值

* @param text

* ? ? ? ? ? ?文字

* @param keyword

* ? ? ? ? ? ?文字中的關鍵字數組

* @return

*/

public static SpannableString matcherSearchTitle(int color, String text,

String[] keyword) {

SpannableString s = new SpannableString(text);

for (int i = 0; i < keyword.length; i++) {

Pattern p = Pattern.compile(keyword[i]);

Matcher m = p.matcher(s);

while (m.find()) {

int start = m.start();

int end = m.end();

s.setSpan(new ForegroundColorSpan(color), start, end,

Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

}

}

return s;

}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容