TextView部分字型變紅

2021-06-22 12:46:37 字數 1515 閱讀 3387

android textview改變部分文字的顏色和string.xml中文字的替換

一:textview元件改變部分文字的顏色:

textview textview = (textview)findviewbyid(r.id.textview);

//方法一:textview.settext(html.fromhtml("紅色其它顏色"));

//方法二: string text = "獲得銀寶箱!"; spannablestringbuilder style=new spannablestringbuilder(text); style.setspan(new backgroundcolorspan(color.red),2,5,spannable.span_exclusive_inclusive); //設定指定位置textview的背景顏色 style.setspan(new foregroundcolorspan(color.red),0,2,spannable.span_exclusive_inclusive); //設定指定位置文字的顏色 textview.settext(style);

二:android string.xml檔案中的整型和string型代替:

string text = string.format(getresources().getstring(r.string.baoxiang), 2,18,"銀寶箱");

對應的string.xml檔案引數:

您今天打了%1$d局,還差%2$d局可獲得%3$s!

%1$d表達的意思是整個name=」baoxiang」字串中,第乙個整型

在專案開發者,經常需要把以上兩者結合起來使用。可以避免很多textview的拼接,如下所示:

textview textview = (textview)findviewbyid(r.id.testview);string text = string.format(getresources().getstring(r.string.baoxiang), 2,18,"銀寶箱"); int index = new int[3]; index[0] = text.indexof("2"); index[1] = text.indexof("18"); index[2] = text.indexof("銀寶箱"); spannablestringbuilder style=new spannablestringbuilder(text); style.setspan(new foregroundcolorspan(color.red),index[0],index[0]+1,spannable.span_exclusive_inclusive); style.setspan(new foregroundcolorspan(color.red),index[1],index[1]+2,spannable.span_exclusive_inclusive); style.setspan(new backgroundcolorspan(color.red),index[2],index[2]+3,spannable.span_exclusive_inclusive); textview.settext(style);

改變textview部分字型顏色

skip to end of metadata go to start of metadata 一 使用spanner textview為需要改變字型顏色的控制項 spannablestringbuilder builder new spannablestringbuilder textview.g...

TextView改變部分字型的大小和顏色及首行縮排

在string.xml檔案中 name text name u3000 u3000描述字段 得到檔案中的字串 string jdsc text string this.getresources getstring r.string text name textview.settext jdsc te...

TextView設定字型樣式

packagecom.zhou.activity import importandroid.graphics.color importandroid.os.bundle importandroid.text.spannable importandroid.text.spannablestring i...