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

วิธีใช้ Fade In และ Fade Out Animation ใน Android ด้วย Java

ภาพรวม

Fade In และ Fade Out Animation ทำงานโดยใช้คลาส AlphaAnimation (สำหรับ Fade In) และ ObjectAnimator (สำหรับ Fade Out) ควบคุมค่า Alpha (ความโปร่งใส) ของ View

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

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

ขั้นตอนที่ 2: เพิ่ม Layout XML

ไฟล์ res/layout/activity_main.xml (แก้จาก login.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/parent"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher" />
    <Button
        android:id="@+id/fadeIn"
        android:text="Fade In"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/fadeOut"
        android:text="Fade Out"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

ขั้นตอนที่ 3: โค้ด Java

ไฟล์ src/MainActivity.java:

package com.example.andy.myapplication;

import android.animation.ObjectAnimator;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        final ImageView imageView = findViewById(R.id.imageView);
        Button fadeIn = findViewById(R.id.fadeIn);
        Button fadeOut = findViewById(R.id.fadeOut);
        
        // Fade In Animation - ใช้ AlphaAnimation (View Animation)
        fadeIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
                alphaAnimation.setDuration(1000);        // 1 วินาที
                alphaAnimation.setRepeatCount(1);        // ทำซ้ำ 1 ครั้ง (รวมครั้งแรก = 2 ครั้ง)
                alphaAnimation.setRepeatMode(Animation.REVERSE);  // ย้อนกลับ (Fade Out แล้ว Fade In)
                imageView.startAnimation(alphaAnimation);
            }
        });
        
        // Fade Out Animation - ใช้ ObjectAnimator (Property Animation)
        fadeOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ObjectAnimator fadeOutAnim = ObjectAnimator.ofFloat(imageView, "alpha", 1f, 0f);
                fadeOutAnim.setDuration(2000);  // 2 วินาที
                fadeOutAnim.start();
            }
        });
    }
}

สองระบบ Animation ใน Android

คุณสมบัติView Animation (AlphaAnimation)Property Animation (ObjectAnimator)
API LevelAPI 1+API 11+ (Honeycomb)
เปลี่ยนคุณสมบัติจริง❌ แค่เปลี่ยนการวาด (Visual only)✅ เปลี่ยน Property จริง
Performanceเบาเร็วหนักกว่า (แต่ทันสมัยกว่า)
Animate ได้Alpha, Scale, Translate, RotateProperty ใดๆ ของ Object
CallbackAnimationListenerAnimatorListener

โค้ดสำหรับ Fade In (AlphaAnimation)

AlphaAnimation fadeIn = new AlphaAnimation(0.0f, 1.0f);  // 0 = โปร่งใส, 1 = ปกติ
fadeIn.setDuration(1000);           // ระยะเวลา (ms)
fadeIn.setRepeatCount(0);           // 0 = ไม่ซ้ำ, -1 = ซ้ำตลอด
fadeIn.setRepeatMode(Animation.RESTART);  // หรือ REVERSE
fadeIn.setFillAfter(true);          // คงสถานะหลังจบ (คง alpha = 1)
imageView.startAnimation(fadeIn);

โค้ดสำหรับ Fade Out (ObjectAnimator)

ObjectAnimator fadeOut = ObjectAnimator.ofFloat(imageView, "alpha", 1f, 0f);
fadeOut.setDuration(1000);
fadeOut.addListener(new AnimatorListenerAdapter() {
    @Override
    public void onAnimationEnd(Animator animation) {
        imageView.setVisibility(View.INVISIBLE);  // ซ่อนจริงหลังจบ
    }
});
fadeOut.start();

🔧 แบบรวม: Fade In แล้ว Fade Out ต่อเนื่อง

AnimatorSet animatorSet = new AnimatorSet();

ObjectAnimator fadeIn = ObjectAnimator.ofFloat(imageView, "alpha", 0f, 1f);
fadeIn.setDuration(1000);

ObjectAnimator fadeOut = ObjectAnimator.ofFloat(imageView, "alpha", 1f, 0f);
fadeOut.setDuration(1000);
fadeOut.setStartDelay(500);  // รอ 0.5 วิหลัง Fade In จบ

animatorSet.playSequentially(fadeIn, fadeOut);
animatorSet.start();

XML Animation (Alternative)

สร้าง res/anim/fade_in.xml:

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="https://schemas.android.com/apk/res/android"
    android:fromAlpha="0.0"
    android:toAlpha="1.0"
    android:duration="1000" />

ใช้งาน:

Animation fadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
imageView.startAnimation(fadeIn);

⚠️ ข้อควรระวัง

  • View Animation (AlphaAnimation) ไม่เปลี่ยน Property จริง - View ยัง clickable ได้แม้จะ invisible
  • Property Animation (ObjectAnimator) เปลี่ยนค่า alpha จริง - ต้องตั้ง visibility เองหลังจบ
  • ใช้ setFillAfter(true) สำหรับ View Animation เพื่อคงสภาพสุดท้าย
  • หน่วยความจำ: ObjectAnimator สร้าง Object ใหม่ ควร reuse หากใช้บ่อย

วิธีทดสอบ

  1. รันแอปบนอุปกรณ์จริง
  2. กด "Fade In" - รูปภาพจะค่อยๆ ชัดเจนขึ้น (0% → 100%)
  3. กด "Fade Out" - รูปภาพจะค่อยๆ จางหาย (100% → 0%)