본격적인 예제에 들어가기 전에, Linkify가 무엇인지 먼저 알아보겠습니다. Linkify는 HTML의 하이퍼링크와 유사한 기능으로, 텍스트 안의 URL이나 이메일 주소 등을 클릭 가능한 링크로 변환해 주는 안드로이드의 유틸리티 클래스입니다. 이 글에서는 안드로이드의 TextView에 Linkify를 적용하는 간단하고 실용적인 방법을 단계별로 살펴봅니다.
1단계: 새 프로젝트 생성하기
Android Studio를 열고 File → New Project 메뉴로 이동한 뒤, 필요한 모든 정보를 입력하여 새 프로젝트를 생성합니다.
2단계: 레이아웃 파일 작성하기
다음 코드를 res/layout/activity_main.xml에 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result Data"
android:textSize="20sp"
android:padding="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>위 XML 코드에는 하나의 TextView가 정의되어 있으며, 이 TextView에는 일반 텍스트와 웹 URL이 함께 들어갑니다.
3단계: MainActivity에 Linkify 적용하기
다음 코드를 src/MainActivity.java에 추가합니다.
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.util.Linkify;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.result);
textView.setText("TutorialsPoint.com originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their ow...");
Linkify.addLinks(textView, Linkify.WEB_URLS);
}
}위 코드에서는 TextView에 텍스트를 설정하고, 그 안에 tutorialspoint.com이라는 URL을 포함시켰습니다. 안드로이드에서 Linkify를 호출하려면 Linkify.addLinks() 메서드를 사용하며, 이 메서드에는 대상 TextView와 LinkifyMask 값을 인자로 전달해야 합니다.
LinkifyMask의 종류
LinkifyMask에는 여러 가지 유형이 있으며, 각각의 역할은 다음과 같습니다.
- Linkify.WEB_URLS: 텍스트 내의 URL을 웹 링크로 변환합니다. 사용자가 해당 링크를 클릭하면 기본 웹 브라우저로 URL이 전달됩니다.
- Linkify.EMAIL_ADDRESSES: 이메일 주소를 클릭 가능한 링크로 변환합니다. 사용자가 클릭하면 모바일 기기의 기본 이메일 앱이 실행됩니다.
- Linkify.PHONE_NUMBERS: 전화번호를 클릭 가능한 링크로 변환합니다. 사용자가 클릭하면 해당 번호가 기본 다이얼러(전화 앱)로 전달됩니다.
- Linkify.ALL: WEB_URLS, EMAIL_ADDRESSES, PHONE_NUMBERS 세 가지 마스크를 모두 한 번에 처리합니다.
4단계: 매니페스트 설정하기
다음 코드를 manifest.xml에 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.andy.myapplication">
<uses-permission android:name="android.permission.INTERNET"/>
<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>인터넷으로 연결된 웹 페이지를 열어야 하므로 INTERNET 권한이 반드시 선언되어 있어야 합니다.
애플리케이션 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭하세요. 그런 다음 실행할 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

위 출력 화면에서 링크가 적용된 텍스트를 클릭하면, 아래와 같이 웹 브라우저가 실행됩니다.

링크를 클릭하면 아래 출력 화면과 같이 기본 웹 브라우저에서 해당 웹사이트가 열리는 것을 확인할 수 있습니다.

마무리
이처럼 Linkify를 활용하면 별도의 복잡한 처리 없이도 TextView 내의 URL, 이메일 주소, 전화번호를 손쉽게 클릭 가능한 링크로 변환할 수 있습니다. Linkify.addLinks() 메서드와 적절한 LinkifyMask만 지정하면 되므로, 채팅 앱이나 게시판 앱 등 다양한 상황에서 유용하게 활용할 수 있습니다.