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

วิธีสร้าง TextView ที่เลื่อนได้ (Scrollable) ใน Android ด้วย Kotlin

บทนำ

ตัวอย่างนี้สาธิตวิธีทำให้ TextView เลื่อนได้ (Scrollable) เพื่อแสดงข้อความยาวใน Android โดยใช้ Kotlin

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

สร้างโปรเจกต์ใหม่ใน Android Studio

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

เพิ่มโค้ดใน res/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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:scrollbars="vertical"
        android:textColor="@android:color/background_dark"
        android:textSize="48sp"
        android:textStyle="italic" />

</RelativeLayout>

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

เพิ่มโค้ดใน src/MainActivity.kt:

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
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.textView)
        val text: String = "Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma – which is living with the results of other people's thinking. " +
                "If life were predictable it would cease to be life, and be without flavor. The big lesson in life, baby, is never be scared of anyone or anything."

        textView.text = text
        textView.movementMethod = ScrollingMovementMethod() // สำคัญ: เปิดใช้งานการเลื่อน
    }
}

ขั้นตอนที่ 4: AndroidManifest.xml

ตรวจสอบการประกาศ Activity

การทดสอบ

รันแอปบนอุปกรณ์จริง ข้อความยาวจะเลื่อนขึ้น-ลงได้ด้วยการสวาย

วิธีสร้าง TextView ที่เลื่อนได้ (Scrollable) ใน Android ด้วย Kotlin

เคล็ดลับ: ต้องตั้งค่า android:scrollbars="vertical" ใน XML และ textView.movementMethod = ScrollingMovementMethod() ในโค้ด ทั้งคู่จึงจะทำงานได้