Android 一個TextView中設定文字不同字型大小和顏色的最完整方法
阿新 • • 發佈:2019-01-05
在做專案的時候,經常會遇到過一行文字有兩種顏色。有時候直接會想到用多個TextView來實現。今天就介紹一下更為簡單的方法,用一個TextView實現。
效果:
這幾個都實現了一行字有不同顏色,還有兩個字型大小也不一樣,我們下邊一一介紹。
首先xml程式碼:
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textSize="18sp"
android:text="Hello World!"
/>
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textSize="18sp"
android:text ="Hello World!"
/>
<TextView
android:id="@+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textSize="18sp"
android:text="Hello World!"
/>
<TextView
android:id ="@+id/tv4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textSize="18sp"
android:text="Hello World!"
/>
<TextView
android:id="@+id/tv5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textSize="18sp"
android:text="Hello World!"
/>
上圖中的第一個TextView程式碼:
String str1 = "今天<font color='#FF0000'>天氣不錯</font>";
tv1.setText(Html.fromHtml(str1));
第二個TextView將紅色字型變小:
String str2 = "今天<font color='#FF0000'><small>天氣不錯</small></font>";
tv2.setText(Html.fromHtml(str2));
第三個TextView將紅色字型變大:
String str3 = "今天<font color='#FF0000'><big>天氣不錯</big></font>";
tv3.setText(Html.fromHtml(str3));
上邊三種情況都是固定字元的情況,那如果遇到變數該怎麼辦呢?其實也很簡單。第四個TextView程式碼:
String str4 = "天氣不錯";
tv4.setText(Html.fromHtml("今天" + "<font color='#FF0000'>" + str4 + "</font>"));
上面的實現方式都是使用的html標籤的形式,下面我們使用系統自帶的SpannableString來實現。
第五個TextView程式碼:
SpannableString spannableString = new SpannableString("今天天氣不錯");
spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FF0000")), 2, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv5.setText(spannableString);
setSpan方法有四個引數,ForegroundColorSpan是為文字設定前景色,也就是文字顏色。如果要為文字新增背景顏色,可替換為BackgroundColorSpan。第二個引數:2為文字顏色改變的起始位置,spannableString.length()為文字顏色改變的結束位置。最後一個引數為布林型,可以傳入以下四種:
Spanned.SPAN_INCLUSIVE_EXCLUSIVE 從起始下標到終止下標,包括起始下標
Spanned.SPAN_INCLUSIVE_INCLUSIVE 從起始下標到終止下標,同時包括起始下標和終止下標
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE 從起始下標到終止下標,但都不包括起始下標和終止下標
Spanned.SPAN_EXCLUSIVE_INCLUSIVE 從起始下標到終止下標,包括終止下標