編輯:關於 Android 程式設計
Android 的動畫體系可以分成三大類:幀動畫、視圖動畫(也叫補間動畫)和屬性動畫。前兩者常被合稱為補間動畫,而屬性動畫從 Android 3.0(API Level 11)開始才被支持。
幀動畫作用於 Drawable 資源,本質是把一系列 Drawable 按時間順序連續切換,對應的實現類是 AnimationDrawable。
下面用三張表示天氣的圖片組成一組幀:
<animation-list xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@mipmap/ic_sunny" android:duration="200" />
<item android:drawable="@mipmap/ic_slight_drizzle" android:duration="200" />
<item android:drawable="@mipmap/ic_haze" android:duration="200" />
</animation-list>
private void initViews() {
ImageView sampleIv = findViewById(R.id.iv_sample);
sampleIv.setBackgroundResource(R.drawable.wether_list);
final AnimationDrawable animationDrawable =
(AnimationDrawable) sampleIv.getBackground();
sampleIv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
animationDrawable.start();
}
});
}
點擊圖片後,畫面就會按順序輪播不同的帧。

視圖動畫作用在具體的 View 上,做法是連續修改 View 的繪製屬性來呈現變化,主要包含四種:Scale(縮放)、Rotate(旋轉)、Translate(位移)、Alpha(透明度)。
旋轉動畫:
<rotate xmlns:android="https://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%" />
組合動畫(縮放 + 旋轉):
<set xmlns:android="https://schemas.android.com/apk/res/android">
<scale android:fromXScale="0%"
android:fromYScale="0%"
android:toXScale="100%"
android:toYScale="100%"
android:pivotX="50%"
android:pivotY="50%" />
<rotate android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%" />
</set>
final ImageView sampleIv = findViewById(R.id.iv_sample);
final Animation animation = AnimationUtils.loadAnimation(this, R.anim.roate360);
animation.setDuration(1500);
animation.setInterpolator(this, android.R.anim.linear_interpolator);
animation.setRepeatCount(Animation.INFINITE);
sampleIv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sampleIv.startAnimation(animation);
}
});
不同動畫的效果對比:




屬性動畫是本文的重點。它不只作用在 View 上,幾乎可以針對任意對象——哪怕這個對象根本不會出現在屏幕上。本質是在一段時間內連續改變對象的某個屬性值。
視圖動畫只能作用在 View 對象上,而且能力有限:能縮放、能旋轉,卻改不了背景色。更麻煩的是,它只改變了繪製位置,沒有改變 View 本身的位置。所以一個 View 被移動到新位置後,你去點它的新位置是不會響應的,必須回到最初的坐標點擊才有效。
屬性動畫沒有這些限制:任何對象的任何屬性都能拿來做動畫,而且它是真正修改對象本身,事件分發自然在新位置上生效。
當然,視圖動畫的開銷比屬性動畫低,幾行代碼就能搞定。所以如果視圖動畫能滿足需求,也沒必要非上屬性動畫。
showView.setAlpha(0f);
showView.setVisibility(View.VISIBLE);
showView.animate()
.alpha(1f)
.setDuration(300)
.setListener(null);
hideView.animate()
.alpha(0f)
.setDuration(mShortAnimationDuration)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
hideView.setVisibility(View.GONE);
}
});

下面演示如何在切換 Fragment 時加入卡片翻轉效果。
private void flipCard() {
// 已經在背面,直接回退
if (mShowingBack) {
getFragmentManager().popBackStack();
return;
}
mShowingBack = true;
getFragmentManager()
.beginTransaction()
// 自定義進出與回退動畫,按返回鍵時同樣有效果
.setCustomAnimations(
R.animator.card_flip_right_in,
R.animator.card_flip_right_out,
R.animator.card_flip_left_in,
R.animator.card_flip_left_out)
.replace(R.id.container, new CardBackFragment())
.addToBackStack(null)
.commit();
mHandler.post(new Runnable() {
@Override
public void run() {
invalidateOptionsMenu();
}
});
}
動畫資源本質上是 objectAnimator 的組合,例如 card_flip_right_in.xml:
<set xmlns:android="https://schemas.android.com/apk/res/android">
<objectAnimator android:propertyName="alpha"
android:valueFrom="1.0" android:valueTo="0.0"
android:duration="0" />
<objectAnimator android:propertyName="rotationY"
android:valueFrom="-180" android:valueTo="0"
android:duration="@integer/card_flip_time_full" />
</set>
card_flip_left_in.xml 與它幾乎一致,只是 rotationY 的起止角度改為 -180 到 0;card_flip_left_out.xml 則把角度改為 0 到 180。

ViewPager 切換頁面時,可以通過 PageTransformer 自定義過場。
mPager = findViewById(R.id.pager);
mPager.setAdapter(new ScreenSlidePagerAdapter(getFragmentManager()));
// 菜單中切換不同的 Transformer
mPager.setPageTransformer(false, new ZoomPageTransformer());
mPager.setPageTransformer(false, new DepthPageTransformer());
mPager.setPageTransformer(false, null); // 恢復默認
DepthPageTransformer 的核心是按 position 計算位移、縮放與透明度:
public class DepthPageTransformer implements ViewPager.PageTransformer {
@Override
public void transformPage(View page, float position) {
int pageWidth = page.getWidth();
if (position <= -1) {
reset(page);
} else if (position < 0) {
// 屏幕左側的頁面
page.setTranslationX(-position * pageWidth);
page.setScaleX(position * 0.3f + 1f);
page.setScaleY(position * 0.3f + 1f);
page.setAlpha(1 + position * 0.8f);
} else if (position < 1) {
reset(page);
} else {
reset(page);
}
}
private void reset(View page) {
page.setAlpha(1);
page.setTranslationX(0);
page.setScaleX(1);
page.setScaleY(1);
}
}
ZoomPageTransformer 的思路類似,只是把 scaleFactor 限制在 0.85 到 1 之間,並用水平和垂直邊距計算位移,做出「遠近推進」的錯覺。

從縮略圖平滑放大到全屏大圖,是屬性動畫最經典的應用之一。關鍵在於先量出起點和終點的邊界,再用 AnimatorSet 同時驅動 X、Y、SCALE_X、SCALE_Y 四個屬性。
private void zoomImageFromThumb(final View thumbView, int imageResId) {
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}
final ImageView expandedImageView = findViewById(R.id.expanded_image);
expandedImageView.setImageResource(imageResId);
// 計算起點與終點的屏幕坐標
final Rect startBounds = new Rect();
final Rect finalBounds = new Rect();
final Point globalOffset = new Point();
thumbView.getGlobalVisibleRect(startBounds);
findViewById(R.id.container).getGlobalVisibleRect(finalBounds, globalOffset);
startBounds.offset(-globalOffset.x, -globalOffset.y);
finalBounds.offset(-globalOffset.x, -globalOffset.y);
float startScale;
if ((float) finalBounds.width() / finalBounds.height()
> (float) startBounds.width() / startBounds.height()) {
startScale = (float) startBounds.height() / finalBounds.height();
} else {
startScale = (float) startBounds.width() / finalBounds.width();
}
thumbView.setAlpha(0f);
expandedImageView.setVisibility(View.VISIBLE);
expandedImageView.setPivotX(0f);
expandedImageView.setPivotY(0f);
AnimatorSet set = new AnimatorSet();
set.play(ObjectAnimator.ofFloat(expandedImageView, View.X,
startBounds.left, finalBounds.left))
.with(ObjectAnimator.ofFloat(expandedImageView, View.Y,
startBounds.top, finalBounds.top))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X,
startScale, 1f))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y,
startScale, 1f));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.start();
mCurrentAnimator = set;
// 再次點擊時執行完全相反的過程,還原回縮略圖
}
還原動畫只需把起止值對調,並在 onAnimationEnd 中把縮略圖透明度恢復為 1、大圖隱藏即可。

以上就是 Android 動畫體系的核心知識要點:幀動畫解決逐帧播放,視圖動畫解決簡單的視覺變化,屬性動畫則幾乎覆蓋了所有場景。
Android APK 中 XML 的解析與反編譯方法
APK 裡的 XML 為什麼無法直接打開?它是否只是簡單的二進制文件,難道被加密了?而為什麼用 AXMLPrinter2 反編譯時竟然報錯?本文將逐一解答這些疑問。 A
Android 以程式碼動態產生表格版面 TableLayout
除了用 XML 描述版面,TableLayout 也可以完全用程式碼在執行期組出來。這在資料來源是動態二維陣列、行數事先無法確定的情況下特別方便。 程式碼 packa
Android 接入支付寶支付:從申請商家帳號到 RSA 簽章配置的完整流程
行動支付的普及,讓「付款」幾乎成了每個商業類 App 的標配。過去支付模組不在我負責的範圍內,總覺得那是塊硬骨頭;直到這次專案由我承接訂單模組,真正動手之後才發現——只要
Android 開發筆記(十四):ListView 用法、三種監聽與 Adapter 綁定
Adapter 是什麼角色 Adapter 是資料與視圖之間的橋樑。資料先在 Adapter 裡被整理成列表能吃的形狀,再由 ListView 逐行取出、填充到畫面上。一