Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 下拉刷新動畫自製實作(含圖片放大與位移效果)

編輯:關於 Android 程式設計

Pull-to-refresh 已經是行動應用的標準互動模式,微博、微信、QQ 都在用。這個範例實作一個下拉刷新動畫,並額外加上圖片縮放、透明度變化與位移等效果——這些手法在其他場合也經常派得上用場。

效果影片:https://v.youku.com/v_show/id_XNjY0MTQzODQ4.html

Java 程式碼

package com.buptfarmer.devapp;

import static com.nineoldandroids.view.ViewPropertyAnimator.animate;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.view.ViewHelper;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.View.OnTouchListener;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class PullAnimationExample extends Activity {

    private TextView mRefreshText;
    private TextView mAaaText;
    private ImageView mHeaderImg;
    private LinearLayout mBottom;
    private LinearLayout mHolder;

    private int mCount;
    private RotateAnimation mFlipAnimation;
    private RotateAnimation mReverseFlipAnimation;

    private int mSlop;
    private boolean mSwiping;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 取得系統定義的觸控最小位移閾值
        ViewConfiguration vc = ViewConfiguration.get(this);
        mSlop = vc.getScaledTouchSlop();

        initView();

        mFlipAnimation = new RotateAnimation(0, -180,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        mFlipAnimation.setFillAfter(true);

        mReverseFlipAnimation = new RotateAnimation(-180, 0,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        mReverseFlipAnimation.setFillAfter(true);
    }

    private void initView() {
        setContentView(R.layout.pull_animation_example);

        mHolder = (LinearLayout) findViewById(R.id.holder);
        mHeaderImg = (ImageView) findViewById(R.id.header_img);
        ViewHelper.setAlpha(mHeaderImg, 0.3f);

        mRefreshText = (TextView) findViewById(R.id.refresh);
        mRefreshText.setVisibility(View.INVISIBLE);

        mAaaText = (TextView) findViewById(R.id.aaa);
        mBottom = (LinearLayout) findViewById(R.id.buttom);

        mHolder.setOnTouchListener(new OnTouchListener() {
            private float mDownX;
            private float mDownY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {

                    case MotionEvent.ACTION_DOWN: {
                        mDownX = event.getX();
                        mDownY = event.getY();
                        mRefreshText.setVisibility(View.VISIBLE);
                        mRefreshText.setText("pull to refresh");
                        break;
                    }

                    case MotionEvent.ACTION_MOVE: {
                        float deltaX = Math.abs(event.getX() - mDownX);
                        float deltaY = Math.abs(event.getY() - mDownY);

                        // 位移超過閾值,且垂直移動量明顯大於水平,才判定為下拉手勢
                        if (deltaY > mSlop && deltaY > deltaX) {
                            mSwiping = true;
                            v.getParent().requestDisallowInterceptTouchEvent(true);

                            // 以 header 高度為基準換算比例,並限制上限避免放大過度
                            float percent = Math.min(0.2f,
                                    Math.abs(deltaY) / mHeaderImg.getMeasuredHeight());

                            ViewHelper.setScaleX(mHeaderImg, 1f + 3f * percent);
                            ViewHelper.setScaleY(mHeaderImg, 1f + 3f * percent);
                            ViewHelper.setAlpha(mHeaderImg,
                                    Math.min(1f, 0.3f + 3f * percent));

                            // 下方內容跟手位移
                            ViewHelper.setTranslationY(mBottom, deltaY);

                            // 超過一定距離後改變提示文字
                            if (deltaY > mRefreshText.getHeight()) {
                                mRefreshText.setText("release to refresh");
                            }
                        }
                        break;
                    }

                    case MotionEvent.ACTION_UP: {
                        if (mSwiping) {
                            mSwiping = false;

                            // 復位
                            ViewHelper.setScaleX(mHeaderImg, 1f);
                            ViewHelper.setScaleY(mHeaderImg, 1f);
                            ViewHelper.setAlpha(mHeaderImg, 0.3f);
                            animate(mHeaderImg).alpha(0.3f).scaleX(1f).scaleY(1f)
                                    .setListener(null);
                            animate(mBottom).translationY(0).setListener(null);

                            updateText();

                            mRefreshText.setVisibility(View.INVISIBLE);
                            mRefreshText.setText("refreshing...");
                        }
                        break;
                    }

                    default:
                        break;
                }
                return true;
            }
        });
    }

    /** 更新文字並搭配進場動畫 */
    private void updateText() {
        animateText(mAaaText, new AnimationCallback() {
            @Override
            public void onAnimation() {
                mAaaText.setText("update " + mCount++);
            }
        });
    }

    /** 通用文字切換動畫:先淡出縮小,換字後再淡入放大 */
    public static void animateText(final View view, final AnimationCallback callback) {
        int origHeight = view.getHeight();

        animate(view).translationY(origHeight).alpha(0).scaleX(0.5f).scaleY(0.5f)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        if (callback != null) {
                            callback.onAnimation();
                        }
                        animate(view).translationY(0).alpha(1).scaleX(1f).scaleY(1f)
                                .setListener(null);
                    }
                });
    }

    public interface AnimationCallback {
        public void onAnimation();
    }
}

版面配置

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/holder"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="fill_parent">

        <ImageView
            android:id="@+id/header_img"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:src="@drawable/all_in_one" />

        <TextView
            android:id="@+id/refresh"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:text="pull to refresh"
            android:textColor="@color/blue"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/aaa"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/refresh"
            android:layout_centerHorizontal="true"
            android:text="aaaaaa text"
            android:textColor="@color/red"
            android:textSize="20sp" />

        <LinearLayout
            android:id="@+id/buttom"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/header_img"
            android:gravity="center_horizontal"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="bbbbbb text"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="bbbbbb text"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="bbbbbb text"
                android:textSize="20sp" />
        </LinearLayout>
    </RelativeLayout>
</LinearLayout>

幾個關鍵設計點

用系統的 touch slop 而非自訂門檻。ViewConfiguration.getScaledTouchSlop() 取得的值是 Android 判斷「使用者是否已開始拖動」的官方標準,在不同裝置與不同使用者偏好設定下都能給出合適的門檻。自訂固定像素值在高低解析度螢幕上表現會不一致。

判斷手勢方向。原始程式碼只檢查 deltaY > mSlop,這會導致水平滑動時也被誤判為下拉。上面已補上 deltaY > deltaX 的條件,確保只有明顯垂直的移動才觸發。

requestDisallowInterceptTouchEvent 的必要性。若父層是 ListView、ViewPager 或任何會攔截觸控事件的容器,不主動呼叫這個方法,下拉手勢會在中途被父層搶走,導致動畫做一半就中斷。

percent 的上限保護。用 Math.min(0.2f, ...) 限制比例,避免使用者大幅拖動時圖片被放大到超出畫面。這種「跟手但有阻尼」的手感是下拉動畫設計的關鍵。

nineoldandroids 的角色。範例使用 nineoldandroids 是為了相容 API 8 以下的裝置。若專案的 minSdk 已高於 11,可以直接改用系統原生的 ViewPropertyAnimator 與 View.setScaleX / setAlpha / setTranslationY,省去這個相依性。

實際產品中的差異

這個範例是互動原型,距離量產還有一段路:真正的下拉刷新元件通常會實作 SwipeRefreshLayout 那樣的「閾值判斷 + 觸發回呼 + 載入中狀態」三段式流程,並把刷新邏輯以 listener 形式對外暴露。若只是要功能,直接用官方 SwipeRefreshLayout 即可;這個實作的價值在於展示如何自己控制縮放、透明度與位移的連動關係——那些客製化視覺效果是官方元件無法直接提供的。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved