想讓介面活潑一點,跳躍效果是個成本不高、回報率卻不錯的選擇。做法的核心是:讓前景 View 上下跳動,同時讓一個作為影子的背景 View 做同步縮放,營造出「離地越高、影子越淡越小」的錯覺。
我採用透明漸層的灰黑色背景,因此不能再搭配黑色主題,改為 Theme.Light:
android:theme="@android:style/Theme.Light"
因為影子與前景必須堆疊在同一位置,RelativeLayout 是最合適的容器:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/imageViewShadow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignBottom="@+id/imageViewItem"
android:layout_marginBottom="-5px"
android:src="@drawable/shadow" />
<ImageView
android:id="@+id/imageViewItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/test" />
</RelativeLayout>
第一是順序:在 XML 中必須先放背景(影子)、後放前景,因為後加入的 View 會畫在上層,這樣影子才不會蓋住主體。
第二是位置:影子與前景底部對齊,並以負的 layout_marginBottom 向下縮進幾個像素,落地時才會露出薄薄一層陰影。若你希望跳起時影子有「變小變淡」的變化,可在動畫中對影子同步套用 scale 與 alpha,並讓它的變化幅度與前景的位移量成正比。
若只是簡單上下跳,用 ObjectAnimator 搭配 translationY 與 AccelerateDecelerateInterpolator 就綽綽有餘;想一次驅動多個屬性並保證時序一致,改寫成一次AnimatorSet 會比分別啟動兩個動畫更好維護,也能避免影子與本體因為啟動時間差而產生偏移。