Android之屬性動畫

來源:互聯網
上載者:User

Android之屬性動畫

一、概述

  Android平台中常用的動畫主要有兩類,一類是View動畫,一類是3.0後新增的屬性動畫。屬性動畫與View動畫相比功能更加強大,主要體現在以下兩個方面:

1、 屬性動畫不僅僅能應用到View上,還可以應用到Object對象上。

2、 屬性動畫將會真正改變Object對象屬性的值。

  如此強大的動畫,我們沒有理由不去學習使用,下面我們就根據API文檔的介紹開始學習如何使用屬性動畫。

二、屬性動畫的學習與使用

  首先我們要先瞭解屬性動畫的一些關鍵屬性,文檔中給出了這麼幾個:

Duration:這個很好理解,動畫的期間。

Time interpolation:時間差值,主要用來定義動畫的變動率,系統中已經提供許多定義好的插值器,具體可以參照下表:

Repeat count and behavior:重複次數和模式,用於定義說明動畫的重複次數及如何重複。

Animator sets:動畫集合,用於組合動畫,可以指定動畫的執行順序。

Frame refresh delay:刷幀延遲。

  瞭解了這些屬性的意義後,我們在來看看與屬性動畫相關的類有哪些,從表中我們可以看到主要有3個,分別是ValueAnimator、ObjectAnimator、AnimatorSet,其中ObjectAnimator是ValueAnimator的子類。

  大多數情況下我們使用ObjectAnimator即可方便的完成非常不錯的動畫效果,下面讓我們先體驗一下。先上布局檔案,非常簡單,只有一張圖片和一個按鈕。


 

  Java:


findViewById(R.id.btnOK).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ObjectAnimator .ofFloat(imageView, translationX, 0f,300f) .setDuration(2000) .start(); } });

  如下:

  通過以上的示範,我們可以看到使用ObjectAnimator可以非常方便的完成一個動畫,僅僅一行代碼,同時通過Toast我們可以看出圖片的位置屬性確實是改變了。

  我們具體瞭解一下ObjectAnimator,ObjectAnimator提供了ofInt、ofFloat、ofObject等方法,這些方法中基本都需要如下參數:

Object target:動畫作用的目標對象。

String propertyName:動畫的作用屬性,注意目標對象必須為此屬性提供get/set方法。

Float/int… values:可變參數,用於定義動畫的起始、中間、結束時的數值。

  預設情況下,動畫變化效果是線性,我們可以通過setInterpolator方法設定一個插值器來改變動畫的變動率。

  AnimatorSet:用於組合動畫 ,下面我們通過一個例子來示範它的具體用法,主要代碼如下:


AnimatorSet animatorSet = new AnimatorSet(); ObjectAnimator animator1 = ObjectAnimator.ofFloat(imageView, x, 0,screenWidth-imgWidth); animator1.setDuration(2000); animator1.setInterpolator(new DecelerateInterpolator()); ObjectAnimator animator2 = ObjectAnimator.ofFloat(imageView, y, 0,screenHeight-imgHeight); animator2.setDuration(2000); animator2.setInterpolator(new AccelerateInterpolator()); ObjectAnimator animator3 = ObjectAnimator.ofFloat(imageView, x, screenWidth-imgWidth,0); animator3.setDuration(2000); animator3.setInterpolator(new AccelerateInterpolator()); ObjectAnimator animator4 = ObjectAnimator.ofFloat(imageView, y, screenHeight-imgHeight,0); animator4.setDuration(2000); animator4.setInterpolator(new AccelerateInterpolator()); animatorSet.play(animator1); animatorSet.play(animator2).after(animator1); animatorSet.play(animator3).after(animator2); animatorSet.play(animator4).after(animator3); animatorSet.start();

  通過以上代碼,我們可以看到通過AnimatorSet,我們可以任意組合動畫,並且安排它們的執行順序,圖片在螢幕中按照順時針方向走一周,並且因為插值器的使用,其變動率不一樣,執行效果如下:

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.