一段文字中的幾個關鍵字顯示高亮

來源:互聯網
上載者:User

標籤:string

將一段文字中的幾個關鍵字顯示高亮

樣本:將“我的願望是當個綠巨人,所以我想讓我的皮(derma)膚是綠色”中的”皮膚“顯示綠色。


<span style="font-size:18px;">public class MainActivity extends Activity {private static TextView mTextView;//需要顯示的文字private static String keywords="皮(.*)膚";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mTextView=(TextView)findViewById(R.id.tv_moder);        //調用TextUtilTools類的highlight方法        SpannableStringBuilder textString = TextUtilTools.highlight(        mTextView.getText().toString(), keywords);        //修改文本顯示內容mTextView.setText(textString);           }        public static class TextUtilTools {    /**     * @param text 要顯示的內容     *      * @param target 要高亮顯示的內容     * @param SpannableStringBuilder 類似於String,比String多了可以給文字添加樣式(顏色,底線···)     **/public static SpannableStringBuilder highlight(String text,String target) {SpannableStringBuilder spannable = new SpannableStringBuilder(text);//字型樣式CharacterStyle span = null;//將keywords作為一個模板 Pattern pattern=Pattern.compile(keywords); //匹配器     Matcher matcher =pattern.matcher(mTextView.getText());while (matcher.find()) {span = new ForegroundColorSpan(Color.GREEN);// 需要重複!//設定spannable中的關鍵字spannable.setSpan(span, matcher.start(), matcher.end(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);}//spannable.setSpan(new ClickableSpan() {//@Override//public void onClick(View arg0) {//MethodsExtra.startActivity(mContext,HouseManageActivity.class);}//}, 0, 0, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);return spannable;}}}</span>

啦啦~啦~~啦~~~,今天剛學會的,曬給大家!!!

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

一段文字中的幾個關鍵字顯示高亮

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.