Android TextView에서 여러 스타일 적용하기
이 예제는 하나의 TextView 안에서 굵게(bold), 기울임(italic), 작은 글꼴(small), 글자 색상(font color) 등 여러 스타일을 동시에 적용하는 방법을 보여줍니다. 핵심은 Html.fromHtml()을 이용해 HTML 태그가 포함된 문자열을 Spanned 형태로 변환하는 것입니다.
TextView에 여러 스타일을 넣는 방법은 두 가지가 있습니다. 첫째, 자바 코드에서 직접 HTML 문자열을 지정하는 방식이고, 둘째, strings.xml 리소스 파일에 CDATA 블록으로 HTML 태그를 정의한 뒤 불러오는 방식입니다. 아래에서 두 가지 방법을 모두 살펴보겠습니다.
1단계 — 새 프로젝트 생성
Android Studio에서 File → New Project를 선택하고, 필요한 정보를 모두 입력하여 새 프로젝트를 만듭니다.
2단계 — 레이아웃 작성(activity_main.xml)
res/layout/activity_main.xml에 다음 코드를 추가합니다. 세 개의 TextView를 RelativeLayout으로 배치했습니다.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_above="@id/textView2"
android:layout_marginBottom="16dp"
android:id="@+id/textView1"
android:textSize="16dp"
android:padding="4dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:padding="4dp"
android:layout_centerInParent="true"/>
<TextView
android:layout_below="@id/textView2"
android:layout_marginTop="16dp"
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:padding="4dp"/>
</RelativeLayout>3단계 — MainActivity.java 작성
src/MainActivity.java에 다음 코드를 추가합니다. 첫 번째와 두 번째 TextView에는 코드에서 직접 HTML 문자열을 적용하고, 세 번째 TextView에는 strings.xml에 정의한 문자열 리소스를 적용합니다.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView1, textView2, textView3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = findViewById(R.id.textView1);
textView2 = findViewById(R.id.textView2);
textView1.setText(Html.fromHtml("Multiple style inside android textView: bold text: "
+ "<b>bold text</b>, italic text: <i>italic text</i>, small font: <small>small "
+ "text</small>, "
+ "font color: <font color=\"blue\">Text Color</font>, "
+ "font color with bold text: <fontcolor=\"green\"><b>Bold with font "
+ "color</b></font>"));
Spanned text = Html.fromHtml("Multiple style inside android textView: bold text: "
+ "<b>bold text</b>, "
+ "italic text: <i>italic text</i>, small font: <small>small text</small>, font "
+ "color: <font color=\"blue\">Text Color</font>, "
+ "font color with bold text: <fontcolor=\"green\"><b>Bold with font "
+ "color</b></font>");
textView2.setText(text);
textView3 = findViewById(R.id.textView3);
textView3.setText(Html.fromHtml(getString(R.string.textStyle)));
}
}4단계 — 문자열 리소스 추가(strings.xml)
res/values/strings.xml 파일을 열고 다음 코드를 추가합니다. CDATA 블록 안에 HTML 태그를 그대로 작성하면 코드를 더 깔끔하게 관리할 수 있습니다.
<resources>
<string name="app_name">Sample</string>
<string name="textStyle">
<![CDATA[
Multiple style inside android textView: bold text: <b>bold
text</b>, italicText text: <i>italic text</i>, small font:
<small>small text</small>,
font color: <font color="blue"<Text Color</font<, font
color with bold text: <font color="green"><b>Bold with font
color</b></font>
]]>
</string>
</resources>5단계 — AndroidManifest.xml 설정
androidManifest.xml에 다음 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>실행 결과 확인하기
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run(실행) 아이콘을 클릭하고, 목록에서 본인의 모바일 기기를 선택하세요. 그러면 기기 화면에 아래와 같이 여러 스타일이 적용된 TextView가 표시됩니다.

추가 팁
API 24(누가) 이상을 대상으로 한다면, deprecated된 단일 인자 버전 대신 Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY)처럼 플래그를 지정하는 버전을 사용하는 것이 좋습니다. 또한 글자 크기는 16dp보다 16sp 단위를 사용하는 것이 사용자 시스템 글꼴 크기 설정을 반영하므로 접근성 측면에서 권장됩니다.