2019年4月19日 星期五

[Android] TextView 中顯示不同字體大小

效果如下


這時就要透過Spannable 來做對應的處理

TextView textView=(TextView)findViewById(R.id.txt);

String str="您今天已經寫了100行書法";
//找到數字1的位置
int startIndex = str.indexOf('1');
//數字只有3個所以是startIndex+2
int endIndex = startIndex+2;
//初始化Spannable
Spannable textSpan = new SpannableStringBuilder(str);
//將數字1之前的字串,字體大小設為28 像素
textSpan.setSpan(new AbsoluteSizeSpan(28), 0, startIndex, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
//將數字100字體大小設為45 像素
textSpan.setSpan(new AbsoluteSizeSpan(45), startIndex, endIndex+1 , Spannable.SPAN_INCLUSIVE_INCLUSIVE);
//將100之後的內容字體大小設為28像素
textSpan.setSpan(new AbsoluteSizeSpan(28), endIndex+1 , str.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
//將Spannable設定給TextView
textView.setText(textSpan);

若要使用dip做為單位,則可以改成如下


TextView textView=(TextView)findViewById(R.id.txt);

String str="您今天已經寫了100行書法";
//找到數字1的位置
int startIndex = str.indexOf('1');
//數字只有3個所以是startIndex+2
 int endIndex = startIndex+2;
//初始化Spannable
Spannable textSpan = new SpannableStringBuilder(str);
//將數字1之前的字串,字體大小設為28
textSpan.setSpan(new AbsoluteSizeSpan(28,true), 0, startIndex, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
//將數字100字體大小設為45
textSpan.setSpan(new AbsoluteSizeSpan(45,true), startIndex, endIndex+1 , Spannable.SPAN_INCLUSIVE_INCLUSIVE);
//將100之後的內容字體大小設為28
textSpan.setSpan(new AbsoluteSizeSpan(28,true), endIndex+1 , str.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
//將Spannable設定給TextView
textView.setText(textSpan);



以下有針對幾個範圍的設定值做出解釋,但試起來還是有點怪怪的,多包函。

Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
不包含StartIndex及EndIndex
Spans of type SPAN_EXCLUSIVE_EXCLUSIVE do not expand to include text inserted at either their starting or ending point.

Spanned.SPAN_EXCLUSIVE_INCLUSIVE
不包含startIndex , 但包含endIndex
Non-0-length spans of type SPAN_EXCLUSIVE_INCLUSIVE expand to include text inserted at their ending point but not at their starting point.

Spanned.SPAN_INCLUSIVE_EXCLUSIVE
包含startIndex 但不包含endIndex
Non-0-length spans of type SPAN_INCLUSIVE_EXCLUSIVE expand to include text inserted at their starting point but not at their ending point.

Spanned.SPAN_INCLUSIVE_INCLUSIVE
包含startIndex及endIndex
Spans of type SPAN_INCLUSIVE_INCLUSIVE expand to include text inserted at either their starting or ending point.





沒有留言:

張貼留言