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

Cách tạo hiệu ứng chuyển đổi màu nền View trên Android bằng Kotlin

Giới thiệu

Bài viết này hướng dẫn cách tạo hiệu ứng animation chuyển đổi màu nền (background color) của một View trên Android sử dụng TransitionDrawable và Kotlin.

Các bước thực hiện

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

Tạo project mới trong Android Studio: File → New Project.

Bước 2: Thiết kế giao diện (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/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    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" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/textView"
        android:layout_centerInParent="true"
        android:layout_marginBottom="15dp"
        android:text="Animate background color" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Changing Background color of this view."
        android:textAlignment="center"
        android:textColor="@android:color/background_dark"
        android:textSize="36sp"
        android:textStyle="bold" />

</RelativeLayout>

Bước 3: Xử lý logic (src/MainActivity.kt)

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.TransitionDrawable
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    private lateinit var textView: TextView
    private lateinit var button: Button

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

        textView = findViewById(R.id.textView)
        button = findViewById(R.id.button)

        button.setOnClickListener {
            // Tạo mảng các ColorDrawable
            val colorDrawables = arrayOf(
                ColorDrawable(Color.GREEN),
                ColorDrawable(Color.RED),
                ColorDrawable(Color.YELLOW)
            )

            // Tạo TransitionDrawable từ mảng màu
            val transitionDrawable = TransitionDrawable(colorDrawables)

            // Gán làm background của TextView
            textView.background = transitionDrawable

            // Bắt đầu animation trong 2000ms (2 giây)
            transitionDrawable.startTransition(2000)
        }
    }
}

Bước 4: Cấu hình Manifest (androidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.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>

Chạy ứng dụng

Kết nối thiết bị thật, nhấn Run. Khi nhấn nút "Animate background color", TextView sẽ chuyển đổi màu nền từ xanh → đỏ → vàng trong 2 giây.

Giải thích

TransitionDrawable là một Drawable đặc biệt cho phép cross-fade giữa các layer Drawable. Mỗi lần gọi startTransition(duration), nó sẽ chuyển từ layer hiện tại sang layer tiếp theo theo thứ tự trong mảng.

Mở rộng

Để lặp lại animation vô hạn hoặc quay lại màu ban đầu, bạn có thể sử dụng ObjectAnimator hoặc ValueAnimator kết hợp với ArgbEvaluator để có kiểm soát linh hoạt hơn.