Hướng dẫn tạo drawableAnimation cho ứng dụng android
Drawable Animation là tạo hiệu ứng chuyển động (giống như việc tạo ảnh gif) cho một đối tượng drawable, từ đó có thể dụng drawable cho imageview....
Bước 1: Chuẩn bị ảnh ít nhất 2 cái cho vào thư mục drawable
Giả sử có 2 ảnh jpg là: a1.jpg và a2.jpg, bạn copy vào thư mục res/drawable
Bước 2: Tạo file drawable
Kích phải chuột lên thư mục drawable --> chọn New --> Drawable Resource File --> đặt tên anh_dong và bấm Enter để tạo file anh_dong.xml
Viết nội dung cho file ảnh động như sau:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- ảnh thứ nhất chạy với thời gian là 2s, ảnh thứ 2 chạy với thời gian là 1s -->
<item android:drawable="@drawable/a1"
android:duration="2000"/>
<item android:drawable="@drawable/a2"
android:duration="1000"/>
</animation-list>
Bước 3: Viết code java
Giả sử bạn tạo 1 cái image view sau đó bấm vào imageview thì sẽ load ảnh động
<ImageView android:id="@+id/img01" android:layout_width="98dp" android:layout_height="76dp" />
Trong hàm onCreate của activity bạn khai báo image
ImageView img01 = findViewById(R.id.img01);
Tiếp theo bạn có thể viết trong sự kiện click vào ảnh hoặc viết ở ngay hàm oncreate cũng được
Code load ảnh động như sau (trường hợp này dùng cơ chế background)
img01.setBackgroundResource(R.drawable.anh_dong);
AnimationDrawable animationDrawable = (AnimationDrawable) img01.getBackground();
animationDrawable.start();
Nguồn: zezo.dev