一起學android之如何設定TextView中不同欄位的字型顏色(22)

來源:互聯網
上載者:User

標籤:spannable   spannablestringbuild   android   textview   字型顏色   

在這裡先看看:



OK,有時候,在我們的項目中會要求TextView中文本有一部分的字型顏色不一樣,這時我們應該使用


SpannableStringBuilder這個工具類,當然這個類的功能很強大,這裡我只是實現上面的樣式,其它的不做介紹,


SpannableStringBuilder的實現介面是Spannable這個介面,而Spannable最終都實現了CharSequence,因此我們直


接可以通過TextView.setText()來進行設定。


下面給出實現代碼:

public class StringFormatUtil {private SpannableStringBuilder spBuilder;private String wholeStr, highlightStr;private Context mContext;private int color;private int start = 0, end = 0;/** *  * @param context * @param wholeStr 全部文字 * @param highlightStr 改變顏色的文字 * @param color 顏色 */public StringFormatUtil(Context context,String wholeStr,String highlightStr,int color){this.mContext=context;this.wholeStr=wholeStr;this.highlightStr=highlightStr;this.color=color;}public StringFormatUtil fillColor(){if(!TextUtils.isEmpty(wholeStr)&&!TextUtils.isEmpty(highlightStr)){if(wholeStr.contains(highlightStr)){/* *  返回highlightStr字串wholeStr字串中第一次出現處的索引。 */start=wholeStr.indexOf(highlightStr);end=start+highlightStr.length();}else{return null;}}else{return null;}spBuilder=new SpannableStringBuilder(wholeStr);color=mContext.getResources().getColor(color);CharacterStyle charaStyle=new ForegroundColorSpan(color);spBuilder.setSpan(charaStyle, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);return this;}public SpannableStringBuilder getResult(){if (spBuilder != null) {return spBuilder;}return null;}}

當然上面的第一步是擷取你要改變顏色的文字的起始位置到結束位置,接著通過SpannableStringBuilder來改變文字

的顏色。


public class MainActivity extends Activity {private TextView tv_show;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();}private void initView() {tv_show = (TextView) findViewById(R.id.tv_show);String wholeStr = "想要改變後面的顏色這是要改變的顏色";StringFormatUtil spanStr = new StringFormatUtil(this, wholeStr,"這是要改變的顏色", R.color.blue).fillColor();tv_show.setText(spanStr.getResult());}}



轉載請註明出處:http://blog.csdn.net/hai_qing_xu_kong/article/details/44225955 情緒控_

一起學android之如何設定TextView中不同欄位的字型顏色(22)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.