Bài giảng Android nâng cao - Bài 6: Animations & Widgets

pdf 26 trang Gia Huy 16/05/2022 1470
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng Android nâng cao - Bài 6: Animations & Widgets", để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên

Tài liệu đính kèm:

  • pdfbai_giang_android_nang_cao_bai_6_animations_widgets.pdf

Nội dung text: Bài giảng Android nâng cao - Bài 6: Animations & Widgets

  1. M o b i P r o ANDROID NÂNG CAO BÀI 6: Animations & Widgets
  2. M o b i P r o Nội dung . Animations – Nguyên tắc – XML vs Code – Interpolator – Drawable Animation . Widgets – Khái niệm – Các bước thực hiện – Các chú ý – Ví dụ về widget có tương tác TRƯƠNG XUÂN NAM 2
  3. M o b i P r o Phần 1 Animations TRƯƠNG XUÂN NAM 3
  4. M o b i P r o Animations – nguyên tắc . Animation: tập hợp các API cho phép biến đổi các view trong một thời gian ngắn (từ android 3.0) . Tạo animation theo nhiều cách – Định nghĩa trong XML (folder “res/anim/”) và nạp bởi câu lệnh AnimationUtils.loadAnimation – Tự tạo bằng cách new các đối tượng phù hợp . Các animation có thể ghép với nhau thành để thực hiện nhiều hiệu ứng (gọi là AnimationSet) . (advanced) Có thể tự tạo custom animation bằng cách kế thừa class Animation và viết lại phương thức applyTransformation 4
  5. M o b i P r o Animations – nguyên tắc . Các animation được cung cấp bởi Android – AlphaAnimation: Thay đổi độ trong suốt của đối tượng • Fade In / Fade Out • Blink – RotateAnimation: Xoay đối tượng – ScaleAnimation: Thay đổi kích thước • Zoom In / Zoom Out • Slide Up / Slide Down • Bounce – TranslateAnimation: Dịch chuyển đối tượng . Bằng cách điều chỉnh các tham số ta có thể tạo các animation khác nhau 5
  6. M o b i P r o Animations – XML vs Code . Ví dụ về XML: res/animator/fadein.xml // nạp animation từ XML để sử dụng Animation ani = AnimationUtils.loadAnimation(this, R.animator.fadein); . Ví dụ tạo animation bằng code: Animation ani = new AlphaAnimation(1, 0); ani.setInterpolator(new AccelerateInterpolator()); ani.setDuration(1000); . Sử dụng animation: myView.startAnimation(ani); 6
  7. M o b i P r o Animations – XML vs Code Một số thuộc tính quan trọng – android:duration: thời gian chạy hiệu ứng (ms) – android:startOffset: thời điểm bắt đầu chạy (ms) – android:fillAfter: có giữ lại trạng thái sau hiệu ứng không (true/false) – android:repeatCount: số lần lặp lại hiệu ứng – android:repeatMode: chế độ lặp (RESTART | REVERSE) – android:interpolator: kiểu diễn biến của hiệu ứng • "@android:anim/accelerate_interpolator“ • “@android:anim/ accelerate_decelerate_interpolator” • 7
  8. M o b i P r o Animations – XML vs Code Có thể xử lý sự kiện khi hiệu ứng bắt đầu, kết thúc hoặc lặp lại bằng AnimationListener (3 phương thức cho giai đoạn) rotAni.setAnimationListener(new AnimationListener() { public void onAnimationEnd(Animation arg0) { layerImage.setVisibility(View.INVISIBLE); layerButtons.setVisibility(View.VISIBLE); } public void onAnimationRepeat(Animation arg0) { } public void onAnimationStart(Animation arg0) { } }); 8
  9. M o b i P r o Animations – Interpolator . Interpolator: trình điều khiển quá trình thực hiện hiệu ứng . Một số Interpolator thông dụng: – AccelerateDecelerateInterpolator: chậm-nhanh-chậm – AccelerateInterpolator: nhanh dần – DecelerateInterpolator: chậm dần – CycleInterpolator: lặp lại animation theo chu kì – LinearInterpolator: tuyến tính, không đổi . Có thể tự viết interpolator của mình nếu thích (phải tìm hiểu thêm về Interpolator.Result) TRƯƠNG XUÂN NAM 9
  10. M o b i P r o Animations – set of animations 10
  11. M o b i P r o Animations – example public class MainActivity extends Activity { Animation x; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); x = AnimationUtils.loadAnimation(this, R.animator.abc); } public void btnAni(View v) { View t = findViewById(R.id.editText1); t.startAnimation(x); } } TRƯƠNG XUÂN NAM 11
  12. M o b i P r o Drawable Animation . 3 kiểu animations trong Android: – Property animation: gốc của mọi animation – View animation: animation trên một view và sử dụng một image – Drawable animation: animation trên một view và sử dụng dãy image . Drawable Animation TRƯƠNG XUÂN NAM 12
  13. M o b i P r o Drawable Animation AnimationDrawable rocketAnimation; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image); rocketImage.setBackgroundResource(R.drawable.rocket_thrust); rocketAnimation = (AnimationDrawable) rocketImage.getBackground(); } public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { rocketAnimation.start(); return true; } return super.onTouchEvent(event); } TRƯƠNG XUÂN NAM 13
  14. M o b i P r o Phần 2 Widgets TRƯƠNG XUÂN NAM 14
  15. M o b i P r o Widgets – khái niệm . Widget là phần màn hình nhỏ đặt lên home-screen hoặc lock-screen của thiết bị Android . Widget chạy như một phần của ứng dụng chủ vì thế cần chú ý việc widget sẽ bị hạn chế bởi các quyền cấp cho ứng dụng chủ . Widget sử dụng RemoteView để tạo giao diện . Widget sử dụng BroadcastReceiver để liên lạc . Widget thường cung cấp thông tin hoặc tương tác tối thiểu, tránh lạm dụng widget . Ứng dụng có chứa widget không thể chuyển sang SD card TRƯƠNG XUÂN NAM 15
  16. M o b i P r o Widgets – các bước thực hiện 1. Tạo file layout phù hợp cho màn hình của widget 2. Tạo class kế thừa từ AppWidgetProvider 3. Viết các phương thức cần thiết của widget 4. Tạo file XML mô tả về widget (type = AppWidget Provider) 5. Cập nhật thông tin trong AndroidManifest.xml TRƯƠNG XUÂN NAM 16
  17. M o b i P r o Widgets: layout TRƯƠNG XUÂN NAM 17
  18. M o b i P r o Widgets: code public class MyWatchWidget extends AppWidgetProvider { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { DateFormat format = SimpleDateFormat.getTimeInstance( SimpleDateFormat.MEDIUM, Locale.getDefault()); RemoteViews remoteViews = new RemoteViews( context.getPackageName(), R.layout.mywatch); ComponentName watchWidget = new ComponentName(context, MyWatchWidget.class); remoteViews.setTextViewText(R.id.textview1, "Time = " + format.format(new Date())); appWidgetManager.updateAppWidget(watchWidget, remoteViews); } } TRƯƠNG XUÂN NAM 18
  19. M o b i P r o Widgets: provider Chú ý: • File được đặt trong “res/xml” • Trong file đã quy định sẵn sẽ sử dụng layout nào thông qua thuộc tính “android:initialLayout” • Các thuộc tính “android:minWidth” và “android:minHeight” quy định chiều rộng và chiều cao tối thiểu của widget TRƯƠNG XUÂN NAM 19
  20. M o b i P r o Widgets: AndroidManifest.xml TRƯƠNG XUÂN NAM 20
  21. M o b i P r o Widgets – các chú ý . Thuộc tính android:updatePeriodMillis trong provider nhỏ nhất là 30 phút . Trong trường hợp cần update thường xuyên hơn, sử dụng AlarmManager hoặc service để xử lý background . Sử dụng: android:widgetCategory="keyguard|home_screen" để widget có thể đặt ở cả lock screen và home screen . Chú ý kích thước layout của widget khi nhắm tới các thiết bị đa dạng về độ phân giải (chỉ cung cấp minResizeHeight và minResizeWidth là đủ) TRƯƠNG XUÂN NAM 21
  22. M o b i P r o Ví dụ về widget có tương tác . Hiển thị câu châm ngôn . Refresh bằng nút bấm . Mỗi khi refresh: – Hiển thị câu châm ngôn khác . Cách làm: – Sử dụng BroadcastReceiver để yêu cầu cập nhật – Có thể tách riêng thành 2 class hoặc dùng chung 1 class cho cả Widget và Receiver – Biến dùng chung cần được chia sẻ (vì có thể thuộc các instance khác nhau) TRƯƠNG XUÂN NAM 22
  23. M o b i P r o AndroidManifest.xml TRƯƠNG XUÂN NAM 23
  24. M o b i P r o Viết mã cho widget (1) static final String ACTION_REFRESH = "txnam.sayingwidget.intent.action.REFRESH"; static String[] sayings = { }; static String[] authors = { }; static int position = 0; // xử lý khi nhận được PendingIntent từ Widget @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(ACTION_REFRESH)) { updateContent(context, AppWidgetManager.getInstance(context)); return; } super.onReceive(context, intent); } TRƯƠNG XUÂN NAM 24
  25. M o b i P r o Viết mã cho widget (2) // xử lý khi cập nhật Widget @Override public void onUpdate(Context context, AppWidgetManager app, int[] Ids) { updateContent(context, app); } // tạo PendingIntent với tên action PendingIntent buildPendingIntent(Context context, String action) { Intent intent = new Intent(action); return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } TRƯƠNG XUÂN NAM 25
  26. M o b i P r o Viết mã cho widget (3) // cập nhật hình ảnh trên Widget void updateContent(Context ct, AppWidgetManager app) { RemoteViews remoteViews = new RemoteViews(ct.getPackageName(), R.layout.saying); position++; if (position >= sayings.length) position = 0; remoteViews.setTextViewText(R.id.textView1, sayings[position]); remoteViews.setTextViewText(R.id.textView2, authors[position]); remoteViews.setOnClickPendingIntent(R.id.button1, buildPendingIntent(ct, ACTION_REFRESH)); ComponentName widget = new ComponentName(ct, SayingWidget.class); app.updateAppWidget(widget, remoteViews); } TRƯƠNG XUÂN NAM 26