앱 개발 과정에서 HTML 형식의 텍스트를 화면에 그대로 표시해야 할 때가 종종 있습니다. 이번 글에서는 안드로이드의 TextView에 HTML 콘텐츠를 간단하게 렌더링하는 방법을 단계별로 알아보겠습니다.
1단계 — 새 프로젝트 생성
Android Studio에서 새 프로젝트를 만듭니다. 상단 메뉴에서 File → New Project로 이동한 뒤, 프로젝트 생성에 필요한 정보를 모두 입력하고 진행하세요.
2단계 — 레이아웃 파일 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
xmlns:tools = "https://schemas.android.com/tools"
android:id = "@+id/rootview"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/htmlToTextView"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</LinearLayout>
레이아웃에는 HTML 콘텐츠를 출력할 TextView 하나만 배치했습니다.
3단계 — MainActivity 코드 작성
src/MainActivity.java 파일에 다음 코드를 추가합니다.
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v4.text.HtmlCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
String htmlText = "<h2>What is Android?</h2>\n" + "<p>Android is an open source and Linux-based <b>Operating System</b> for mobile devices such as smartphones and tablet computers. Android was developed by the <i>Open Handset Alliance</i>, led by Google, and other companies.</p>\n" + "<p>Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android.</p>\n" + "<p>The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007 whereas the first commercial version, Android 1.0, was released in September 2008.</p>";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView htmlToTextView = findViewById(R.id.htmlToTextView);
htmlToTextView.setText(HtmlCompat.fromHtml(htmlText, 0));
}
}
핵심 코드 분석
위 예제에서는 HTML 태그가 포함된 문자열을 htmlText 변수에 담아두었고, 이 문자열을 아래 한 줄의 코드로 TextView에 적용했습니다.
htmlToTextView.setText(HtmlCompat.fromHtml(htmlText, 0));
fromHtml() 메서드가 HTML 문자열을 서식 정보가 담긴 Spanned 객체로 변환하면, setText()가 이를 TextView에 출력하는 구조입니다. 두 번째 인자인 0은 플래그(flag) 값으로, 프로젝트 요구 사항에 맞게 조정할 수 있습니다. 예를 들어 FROM_HTML_MODE_LEGACY 또는 FROM_HTML_MODE_COMPACT 같은 옵션을 전달하면 문단 사이의 빈 줄 처리 방식 등을 세부적으로 제어할 수도 있습니다.
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭하세요. 목록에서 사용 중인 모바일 기기를 선택하면, 기기 화면에 다음과 같이 HTML이 서식이 적용된 텍스트로 렌더링되어 표시됩니다.

위 예제에서 확인할 수 있듯이, HTML 태그가 담긴 문자열이 단순한 텍스트가 아니라 제목, 굵게, 기울임 등의 서식이 반영된 형태로 화면에 출력됩니다.