Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Kotlin으로 안드로이드 TextView에 클릭 가능한 링크 만드는 방법 완벽 가이드

이 튜토리얼에서는 Kotlin을 사용하여 안드로이드 앱의 TextView 안에 클릭 가능한 하이퍼링크를 만드는 방법을 단계별로 알아봅니다. TextView에 웹 페이지로 연결되는 링크를 추가하면 사용자가 텍스트를 탭하는 것만으로 외부 사이트나 다른 화면으로 이동할 수 있어 사용자 경험이 크게 향상됩니다.

핵심 원리 이해하기

안드로이드에서 TextView 내부의 링크를 클릭 가능하게 만들려면 두 가지 요소가 필요합니다.

1. 문자열 리소스에 <a href="..."> 태그로 감싼 텍스트 작성
2. 코드에서 LinkMovementMethod를 설정하여 링크 클릭 이벤트 처리 활성화

Step 1 — 새 프로젝트 생성

Android Studio를 실행하고 File → New Project 메뉴로 이동한 후, 빈 프로젝트(Empty Activity)를 선택하고 필요한 모든 세부 정보를 입력하여 새 프로젝트를 생성합니다. 언어는 Kotlin으로 선택해 주세요.

Step 2 — 레이아웃 파일 작성 (activity_main.xml)

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에 링크가 포함된 TextView를 배치합니다.

<?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_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="50dp"
    android:text="Tutorials Point"
    android:textAlignment="center"
    android:textColor="@android:color/holo_green_dark"
    android:textSize="32sp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/textViewLink"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:text="@string/messageWithLink"
    android:textSize="24sp"
    android:textStyle="bold" />

</RelativeLayout>

Step 3 — 문자열 리소스에 링크 추가 (strings.xml)

res/values/strings.xml 파일을 열고 아래와 같이 <a href> 태그로 감싼 문자열을 추가합니다. 이 태그가 있어야 TextView에서 해당 텍스트가 하이퍼링크로 인식됩니다.

<resources>
    <string name="app_name">Your app Name</string>
    <string name="messageWithLink"><a href="https://www.google.com/">Tap here to open Google</a></string>
</resources>

Step 4 — MainActivity.kt에 LinkMovementMethod 설정

src/MainActivity.kt 파일에 아래 코드를 추가합니다. 여기서 가장 중요한 부분은 LinkMovementMethod.getInstance()를 설정하는 것입니다. 이 설정이 없으면 링크가 화면에는 보이지만 실제로 클릭할 수 없습니다.

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.widget.TextView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        val textView: TextView = findViewById(R.id.textViewLink)
        textView.movementMethod = LinkMovementMethod.getInstance()
    }
}

Step 5 — AndroidManifest.xml 확인

AndroidManifest.xml 파일이 아래와 같이 올바르게 구성되어 있는지 확인합니다. 외부 웹사이트로 이동하려면 인터넷 권한이 필요할 수 있으므로, 필요 시 <uses-permission android:name="android.permission.INTERNET" />도 추가하는 것이 좋습니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
    <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 Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 상단 툴바의 Run ▶ 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면 기기에 앱이 설치되고 실행됩니다.

앱이 실행되면 화면 중앙에 "Tap here to open Google"이라는 파란색 밑줄 링크가 표시됩니다. 해당 텍스트를 탭하면 기본 브라우저가 열리고 Google 홈페이지로 이동하는 것을 확인할 수 있습니다.

추가 팁

- XML 대신 코드에서 동적으로 링크를 만들고 싶다면 Html.fromHtml() 또는 Linkify.addLinks()를 활용할 수 있습니다.
- 링크 색상과 밑줄 스타일은 SpannableStringClickableSpan을 사용해 자유롭게 커스터마이징할 수 있습니다.
- 자동 링크 감지를 원한다면 XML 속성 android:autoLink="web"을 사용하는 간단한 방법도 있습니다.