ตัวอย่าง: การแสดงแอนิเมชั่น Slide Down ให้ TextView
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project แล้วกรอกรายละเอียดที่จำเป็น
ขั้นตอนที่ 2: จัดการ Layout (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:gravity="center"
android:layout_height="match_parent">
<TextView
android:id="@+id/text"
android:textSize="20dp"
android:textAlignment="center"
android:layout_width="match_parent"
android:textColor="#ff4500"
android:layout_height="wrap_content"
android:singleLine="true" />
</RelativeLayout>
TextView จะเลื่อนลงมาจากด้านบนไปยังตำแหน่งที่กำหนด
ขั้นตอนที่ 3: เขียนโค้ด MainActivity (src/MainActivity.java)
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView view = findViewById(R.id.text);
view.setText("วิธีแสดง Slide Down เพื่อแสดง TextView animation");
Animation anim = AnimationUtils.loadAnimation(this, R.anim.slide_in_top);
view.startAnimation(anim);
}
}
สร้าง Animation Resource (res/anim/slide_in_top.xml)
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:repeatCount="100">
<translate
android:duration="@android:integer/config_mediumAnimTime"
android:fromYDelta="-100%"
android:toYDelta="0%" />
<alpha
android:duration="@android:integer/config_mediumAnimTime"
android:fromAlpha="0.0"
android:toAlpha="1.0" />
</set>
ไฟล์ slide_in_top.xml กำหนด:
translate: เลื่อนจาก Y = -100% (นอกหน้าจอด้านบน) ไป Y = 0% (ตำแหน่งปกติ)alpha: โปร่งใสจาก 0.0 (มองไม่เห็น) ถึง 1.0 (มองเห็นชัด)fillAfter: คงสถานะสุดท้ายของแอนิเมชั่นrepeatCount: ทำซ้ำ 100 ครั้ง (ในตัวอย่าง)
การทดสอบแอปพลิเคชัน
เชื่อมต่ออุปกรณ์ Android จริง ใน Android Studio คลิกไอคอน Run เลือกอุปกรณ์ แล้วตรวจสอบหน้าจอ

TextView จะเลื่อนลงมาจากด้านบนพร้อมเอฟเฟกต์ Fade In