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

วิธีสร้าง Animated Gradient Background ใน Android

ภาพรวม

สร้างพื้นหลัง Gradient ที่เปลี่ยนสีแบบมีอนิเมชัน (Animated Gradient) โดยใช้ AnimationDrawable (Frame Animation) ร่วมกับ XML Drawable Gradient สร้างเอฟเฟกต์พื้นหลังสวยงาม ไม่ต้องใช้ Code มาก

โครงสร้างไฟล์

res/
├── drawable/
│   ├── gradient_animation.xml      <-- Animation List (หลัก)
│   ├── gradient_purple.xml         <-- Frame 1
│   ├── gradient_amber.xml          <-- Frame 2
│   ├── gradient_green.xml          <-- Frame 3
│   └── gradient_red.xml            <-- Frame 4
├── layout/
│   └── activity_main.xml
└── java/.../MainActivity.java

ขั้นตอนการสร้าง

1. Gradient Frames (res/drawable/gradient_*.xml)

gradient_purple.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <gradient
        android:angle="90"
        android:startColor="#4A148C"
        android:endColor="#D500F9"
        android:type="linear" />
</shape>

gradient_amber.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <gradient
        android:angle="135"
        android:startColor="#FF6F00"
        android:endColor="#FFC400"
        android:type="linear" />
</shape>

gradient_green.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <gradient
        android:angle="0"
        android:startColor="#1B5E20"
        android:endColor="#00E676"
        android:type="linear" />
</shape>

gradient_red.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <gradient
        android:angle="45"
        android:startColor="#B71C1C"
        android:endColor="#FF1744"
        android:type="linear" />
</shape>

2. Animation List (res/drawable/gradient_animation.xml)

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="https://schemas.android.com/apk/res/android"
    android:oneshot="false"> <!-- false = Loop ตลอด -->

    <item
        android:drawable="@drawable/gradient_purple"
        android:duration="3000" /> <!-- 3 วินาที -->

    <item
        android:drawable="@drawable/gradient_amber"
        android:duration="3000" />

    <item
        android:drawable="@drawable/gradient_green"
        android:duration="3000" />

    <item
        android:drawable="@drawable/gradient_red"
        android:duration="3000" />

</animation-list>

คำอธิบาย:

  • android:oneshot="false" = วนลูปตลอด (true = เล่นครั้งเดียวจบ)
  • android:duration = ระยะเวลาแต่ละเฟรม (มิลลิวินาที)
  • Transition ระหว่างเฟรมจะเป็น Cross-fade อัตโนมัติ

3. Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/gradient_animation"> <-- Set Background ที่นี่ -->

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Animated Gradient Background"
        android:textSize="28sp"
        android:textColor="@android:color/white"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

4. MainActivity.java

package com.example.myapplication;

import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

public class MainActivity extends AppCompatActivity {

    private ConstraintLayout constraintLayout;
    private AnimationDrawable animationDrawable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        constraintLayout = findViewById(R.id.constraintLayout);
        
        // ดึง AnimationDrawable จาก Background
        animationDrawable = (AnimationDrawable) constraintLayout.getBackground();
        
        // ตั้งค่า Fade Duration (Optional)
        animationDrawable.setEnterFadeDuration(3000); // Fade in
        animationDrawable.setExitFadeDuration(2000);  // Fade out
    }

    @Override
    protected void onResume() {
        super.onResume();
        // เริ่ม Animation เมื่อ Activity Resume
        if (animationDrawable != null && !animationDrawable.isRunning()) {
            animationDrawable.start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // หยุด Animation เมื่อ Pause (ประหยัด Battery/CPU)
        if (animationDrawable != null && animationDrawable.isRunning()) {
            animationDrawable.stop();
        }
    }
}

Gradient Types (ประเภท Gradient)

Typeandroid:typeคำอธิบาย
Linearlinearเส้นตรงจาก startColor ไป endColor (Default)
Radialradialวงกลมขยายจากศูนย์กลาง (ต้องมี android:gradientRadius)
Sweepsweepหมุนรอบศูนย์กลาง (เหมือนสเปกตรัม)

Radial Gradient Example:

<gradient
    android:type="radial"
    android:gradientRadius="200dp"
    android:startColor="#FF0000"
    android:endColor="#0000FF"
    android:centerX="0.5"
    android:centerY="0.5" />

ทางเลือกทันสมัย: Animated Vector Drawable / Lottie

  • AnimatedVectorDrawable: Vector Path Animation (API 21+), ขนาดเล็ก, รองรับ Morphing
  • Lottie (Airbnb): After Effects → JSON → Render บน Mobile, สวยงาม Complex Animation ได้
  • Jetpack Compose: animateColorAsState, InfiniteTransition สำหรับ Compose UI

Performance Tips

  • ใช้ shape + gradient (Vector) แทน Bitmap → ขนาดเล็ก, Scale ไม่แตก
  • จำนวน Frame ไม่มากเกินไป (4-8 Frames พอ)
  • Duration ไม่น้อยเกินไป (≥ 1000ms) ป้องกัน Jank
  • หยุด Animation ใน onPause/onStop (สำคัญ!)
  • หลีกเลี่ยง nested Animation หลายชั้นพร้อมกัน

สรุป

Animated Gradient Background = AnimationDrawable (animation-list) + Gradient Shapes (XML) → ใส่เป็น Background ของ Layout → เริ่ม/หยุดใน onResume/onPause ใช้ได้กับ View ใดๆ (ConstraintLayout, LinearLayout, CardView, ฯลฯ) เรียบง่าย ประหยัดหน่วยความจำ ไม่ต้องใช้ Library ภายนอก