ตัวอย่าง: การแสดงแอนิเมชั่นการสั่นของ View
ขั้นตอนที่ 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:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:layout_width="150dp"
android:text="คลิก"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/imageView"
android:src="@mipmap/ic_launcher_round"
android:layout_width="match_parent"
android:layout_height="300dp" />
</RelativeLayout>
ในโค้ดข้างต้น เรามี Button เพื่อเริ่มแอนิเมชั่นสั่นให้ ImageView
ขั้นตอนที่ 3: เขียนโค้ด Java (src/MainActivity.java)
package com.example.andy.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = findViewById(R.id.imageView);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Animation animShake = AnimationUtils.loadAnimation(MainActivity.this, R.anim.shake);
view.startAnimation(animShake);
}
});
}
}
สร้าง Animation Resource (res/anim/shake.xml)
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
<translate
android:duration="150"
android:fromXDelta="-10%"
android:repeatCount="5"
android:repeatMode="reverse"
android:toXDelta="10%"/>
</set>
ไฟล์ shake.xml กำหนดแอนิเมชั่น Translate (เลื่อน) ซ้าย-ขวา 10% ซ้ำ 5 รอบ แบบย้อนกลับ (reverse) ระยะเวลา 150ms ต่อรอบ
การทดสอบแอปพลิเคชัน
เชื่อมต่ออุปกรณ์ Android จริง ใน Android Studio คลิกไอคอน Run เลือกอุปกรณ์ แล้วตรวจสอบหน้าจอ

กดปุ่มเพื่อสั่นภาพพื้นหลัง:
