Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีสร้างลิงก์คลิกได้ใน TextView บน Android ด้วย Kotlin

ภาพรวม

ตัวอย่างนี้สาธิตวิธีทำให้ TextView มีลิงก์ที่คลิกได้ (Clickable Links) โดยใช้ LinkMovementMethod และ HTML ใน String Resource

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio เลือก File → New Project

ขั้นตอนที่ 2: Layout (activity_main.xml)

<?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"
    android:padding="16dp"
    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"
        android:autoLink="web|email|phone|map"
        android:linksClickable="true" />

</RelativeLayout>

ขั้นตอนที่ 3: Strings Resource (res/values/strings.xml)

<resources>
    <string name="app_name">Clickable Links Demo</string>
    <string name="messageWithLink"><![CDATA[Visit <a href="https://www.google.com/">Google</a> or email <a href="mailto:support@example.com">Support</a>]]></string>
    <string name="messageWithLink2">Call <a href="tel:+1234567890">Us</a> or find <a href="geo:13.7563,100.5018">Location</a></string>
</resources>

ขั้นตอนที่ 4: MainActivity.kt

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

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

        val textView = findViewById<TextView>(R.id.textViewLink)

        // วิธีที่ 1: ใช้ LinkMovementMethod (สำหรับ HTML ใน String Resource)
        textView.movementMethod = LinkMovementMethod.getInstance()
        
        // วิธีที่ 2: ตั้งค่า HTML โดยโปรแกรม (ถ้าไม่ได้จาก String Resource)
        // val htmlText: Spanned = Html.fromHtml("Visit <a href='https://google.com'>Google</a>", Html.FROM_HTML_MODE_LEGACY)
        // textView.text = htmlText
        // textView.movementMethod = LinkMovementMethod.getInstance()
    }
}

วิธีการทำงานสมัยใหม่ (ClickableSpan)

สำหรับการควบคุมการคลิกแบบกำหนดเอง (Custom Click Handling):

import android.text.SpannableString
import android.text.style.ClickableSpan
import android.text.method.LinkMovementMethod
import android.view.View
import android.widget.Toast

val text = SpannableString("Tap here to open Google")
val clickableSpan = object : ClickableSpan() {
    override fun onClick(widget: View) {
        // จัดการคลิกเอง เช่น เปิดในแอป ไม่ใช่ Browser
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"))
        startActivity(intent)
    }
    
    override fun updateDrawState(ds: TextPaint) {
        super.updateDrawState(ds)
        ds.isUnderlineText = false // ซ่อน Underline
        ds.color = ContextCompat.getColor(this@MainActivity, R.color.link_color)
    }
}

text.setSpan(clickableSpan, 4, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) // "here"
textView.text = text
textView.movementMethod = LinkMovementMethod.getInstance()
textView.highlightColor = Color.TRANSPARENT // ซ่อน Highlight สีเทา

AutoLink ใน XML (ไม่ต้องเขียนโค้ด)

เพิ่ม Attribute ใน TextView XML:

<TextView
    android:autoLink="web|email|phone|map|all"
    android:linksClickable="true"
    android:text="Visit https://google.com or call 123-456-7890" />

ขั้นตอนที่ 5: Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.clickablelinks">
    <application ... >
        <activity android:name=".MainActivity"> ... </activity>
    </application>
</manifest>

การทดสอบ

รันแอป ข้อความ "Visit Google" จะมีสีลิงก์และขีดเส้นใต้ กดจะเปิด Browser ไปที่ Google

หมายเหตุ

  • LinkMovementMethod จำเป็นต้องตั้งค่า ไม่งั้นลิงก์จะไม่คลิกได้
  • ใช้ Html.FROM_HTML_MODE_COMPACT สำหรับ HTML ที่ซับซ้อน (API 24+)
  • ClickableSpan ให้ความยืดหยุ่นสูงสุด (Custom action, Styling)
  • autoLink ตรวจจับ URL/Email/Phone อัตโนมัติจาก Plain Text