Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách thay đổi style TextView tại runtime trong Android bằng Kotlin

Ví dụ này minh họa cách thay đổi kiểu dáng (style) của TextView tại runtime (thời gian chạy) trong Android sử dụng Kotlin.

Bước 1: Tạo dự án mới

Trong Android Studio, chọn File → New Project và điền đầy đủ thông tin để tạo dự án mới.

Bước 2: Cấu hình layout chính (activity_main.xml)

Thêm mã sau vào 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: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="70dp"
        android:background="#008080"
        android:padding="5dp"
        android:text="TutorialsPoint"
        android:textColor="#fff"
        android:textSize="24sp"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Have a nice day!"
        android:textColor="@android:color/background_dark"
        android:textSize="36sp"
        android:textStyle="bold" />
</RelativeLayout>

Bước 3: Định nghĩa style (res/values/styles.xml)

Thêm vào res/values/styles.xml:

<resources>
    <style name="boldText">
        <item name="android:textStyle">bold|italic</item>
        <item name="android:textColor">#FFFFFF</item>
    </style>
    <style name="normalText">
        <item name="android:textStyle">normal</item>
        <item name="android:textColor">#C0C0C0</item>
    </style>
</resources>

Bước 4: Định nghĩa màu sắc (res/values/colors.xml)

Thêm vào res/values/colors.xml:

<resources>
    <color name="highlightedTextViewColor">@android:color/holo_green_light</color>
    <color name="normalTextViewColor">@android:color/holo_red_dark</color>
</resources>

Bước 5: Viết mã MainActivity.kt

Thêm mã sau vào src/MainActivity.kt:

import android.os.Build
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    lateinit var textView: TextView
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        
        textView = findViewById(R.id.textView)
        textView.setOnClickListener {
            if (Build.VERSION.SDK_INT < 23) {
                textView.setTextAppearance(applicationContext, R.style.boldText)
            } else {
                textView.setTextAppearance(R.style.boldText)
            }
            textView.setBackgroundResource(R.color.highlightedTextViewColor)
        }
    }
}

Bước 6: Cấu hình AndroidManifest.xml

<?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>
                
                
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị Android thực với máy tính. Từ Android Studio, mở file activity và nhấn biểu tượng Run trên thanh công cụ. Chọn thiết bị di động và kiểm tra màn hình hiển thị.

Lưu ý: setTextAppearance() từ API 23 (Marshmallow) không còn cần Context parameter. Cách hiện đại hơn: dùng TextAppearanceSpan với SpannableString để thay đổi style một phần văn bản, hoặc dùng textView.setTextAppearance(R.style.YourStyle) trực tiếp (API 23+).